How can I using Dllimport by C# to get string array from C library
int GetClasses (int *NumberofClasses, char *ClassNames[], int arrayLength)
I have try StringBuilder[] and many of MarshalAsAttributes to receive ClassNames but still not work and cause memory violation
I have only explanation of this C method is showing below.
int GetClasses(int * NumberofClasses, char * ClassNames[], int arrayLength)
This function will get the total number of unique classes and each unique class name.
Parameters:
NumberofClasses: Total number of unique classes.
ClassNames: Array of allocated char * to return class names.
arrayLength: Length of passed ClassNames array. If the result exceeds this array length, this function will fail with an error code.
Returns: Zero for success. Non-zero for error
And my declaration is
[DllImport(@".\library.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern Int16 GetClasses(ref UInt16 NumberofClasses, StringBuilder[] ClassNames, UInt16 arrayLength);
I have pass
NumberofClasses=16,
ClassNames= StringBuilder[16] with 256 capacity of each
arrayLength=16
to this call
Finally I got the success call by modify the declaration of parameter type.
[DllImport(@".\library.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern Int16 GetClasses(ref UInt16 NumberofClasses, [In][Out][MarshalAs(UnmanagedType.LPArray)] string[] ClassNames, UInt16 arrayLength);
And allocate a string array to parameter ClassNames
string[] names = new string[NumberOfClasses];
for (int i = 0; i < names.Length; i++)
{
names[i] = new string(new char[256]);
}