Native C string list weak reference to C#

171 views Asked by At

I am creating a .NET adapter for the following C API:

void GetStringList(const char *** listOut, rsize_t * listCountOut);

I want a C# adapter that looks like:

[DllImport("api.dll", CallingConvention = CallingConvention.Cdecl)]
static extern
void GetStringList(
    out string[] listOut,
    out int listCountOut
    );

This doesn't work because the marshaller does not know the out list length is provided by the second parameter. Also, I can't set up an IntPtr, because the length is not known until the function returns.

I can solve this with unsafe.

Is there a better way without unsafe?

1

There are 1 answers

4
jws On

I found a way without unsafe. It is to use IntPtr for the list, followed by drilling down to get list item IntPtrs.

[DllImport("api.dll", CallingConvention = CallingConvention.Cdecl)]
static extern
void GetStringList(
    out IntPtr listOut,
    out int listCountOut
    );

and then something like

IntPtr listOut;
int listCountOut;

GetStringList(out listOut, out listCountOut);

string[] managedList = new string[listCountOut];
for(int i = 0 ; i < listCountOut ; i++)
{
    IntPtr item = Marshal.ReadIntPtr(listOut, i * Marshal.SizeOf(typeof(IntPtr)));
    managedList[i] = Marshal.PtrToStringAnsi(item);
}

Good enough for my purposes.