How to marshal char** in struct?

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.
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top