Marshalling char array.
The C typedef of the function is:
typedef bool (*get_VariableInfoFunc)(int *, char * *, int *, int *);
It`s usage is like:
pnVariableIdArray = new (nothrow) int[numVars];
pcVariableName = new (nothrow) char*[numVars];
for (int i = 0; i < numVars; i++)
{
pcVariableName[i] = new char[100];
}
pnUnVariableIdArray = new (nothrow) int[numVars];
pnVariableType = new (nothrow) int[numVars];
res = get_VariableInfo(pnVariableIdArray, pcVariableName, pnUnVariableIdArray, pnVariableType);
My C# Signature is:
[DllImport(AUTODYNResultsApiDll, EntryPoint = "get_VariableInfo", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetVariableInfo(
int[] pnVariableIdArray,
IntPtr[] pcVariableName,
int[] pnUnVariableIdArray,
int[] pnVariableType);
I use it like:
var stringPointers= new IntPtr[numVars];
for (int i = 0; i < numVars; i++)
{
by[i] = Marshal.AllocHGlobal(100);
}
GetVariableInfo(pnVariableIdArray, stringPointers, pnUnVariableIdArray, pnVariableType);
and then back to string with:
var strings = new string[numVars];
for (int i = 0; i < numVars; i++)
{
strings[i] = Marshal.PtrToStringAnsi(by[i]);
}
Is there a nicer way doing this without freeing the Memory of the pointer. Just copy the char array as string array?