How to marshal char** in struct?

  • Thread starter Thread starter jurot
  • Start date Start date
J

jurot

Hi.

I have struct in C++:

struct MY_STRUCT
{
int x;
int y;
char** arrNames; //array of strings
}

I have function GetMyStruct, which gives me pointer to this struct, but
I can't get the array of strings (MY_STRUCT.arrNames).

MY_STRUCT* GetMyStruct();

In C# :

public struct MY_STRUCT
{
public int x;
public int y;
public string[] arrNames; //array of strings
}

public class MyWrapper
{
[DllImport("MyDll.dll")]
private static extern IntPtr GetMyStruct();
public static MY_STRUCT GetMyStructW()
{
IntPtr p = GetMyStruct();

return (MY_STRUCT) Marshal.PtrToStructure(p, typeof(MY_STRUCT));
}
}


BUT MyWrapper.GetMyStructW() doesn't work. Plllease help.
 
jurot,

There are a few problems with this.

First, to marshal your struct, you will have to declare the arrNames
field as an IntPtr, and then marshal the values manually. You will have a
problem because you don't have any indication (unless you have a null entry
in the array) of when the array ends.

Also, when you are returning the pointer to the structure in
GetMyStruct, you are not deallocating the memory. You need to do this
(using the appropriate method that corresponds to how you allocated it).

Hope this helps.
 
Back
Top