tags:

views:

109

answers:

2

I would like to call this C++ function from my C# code:

void GetArrayOfNames(char** names, int nbOfNames);

To call it in C++, I just define an array of char*:

char* aNames[20];

And allocate each name in a loop:

for(int i-0; i<20; i++)
{
    aNames[i] = new char[50];
}

Then call:

GetArrayOfNames(aNames, 20);

In my C# code, I have:

[DllImport("MyDLL.dll")]
unsafe static extern void GetArrayOfNames(char** ppNames, int nbOfNames);

Now, how do I do the memory allocation and call GetArrayOfNames? Also, any way of not having to declare my function as "unsafe"?

+2  A: 

Probably:

static extern void GetArrayOfNames([MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr] StringBuilder[] args, int count);

// Call using
StringBuilder[] arr = new StringBuilder[20];
for (int i = 0; i < arr.Length; i++)
{
    arr[i] = new StringBuilder(50);
}
GetArrayOfNames(arr, arr.Length);
tyranid
A: 

This ended up working:

static extern int GetArrayOfNames(IntPtr[] astr, int iLength);

And called/setup like this:
IntPtr[] intArr = new IntPtr[200];
for (int i = 0; i < intArr.Length; i++)
{
intArr[i] = Marshal.AllocHGlobal(256);
}

int nbOfNames = 2;
GetArrayOfNames(intArr, nbOfNames);

And to put back in a string:
string tmp;
tmp = Marshal.PtrToStringAnsi(intArr[i]);

Martin