Search code examples
c#.netcmarshalling

Get string array from C using marshalling in C#


My c code is like

void GetCharArray(char* arrayNew[5])
{
    arrayNew[0] = "Test";
    arrayNew[1] = "Test2";
    arrayNew[2] = "Test4";
    arrayNew[3] = "Test5";
    arrayNew[4] = "Test6";
}

extern "C" __declspec(dllexport) void GetCharArray(char* arrayNew[5]);

I want to get the array populated with string in my C# code

[DllImport(@"C:/Test.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern void GetCharArray([MarshalAs(UnmanagedType.LPArray, SizeConst=5)] string[] sbOut);

List<string> testStr = new List<string>();
GetCharArray(test.ToArray());

I want my testStr to be populated with strings from C code.


Solution

  • found a solution

    public static extern void GetCharArray(IntPtr[] results);
    
    IntPtr[] pointers = new IntPtr[1000];
    GetCharArray(pointers);
    string[] results = new string[1000];
    for (int i = 0; i < 1000; i++)
    {
        results[i] = Marshal.PtrToStringAnsi(pointers[i]);
    }
    

    I hope it helps someone else.