0
編組字符數組。C#pinvoke C字符數組
的風格函數的C類型定義是:
typedef bool (*get_VariableInfoFunc)(int *, char * *, int *, int *);
它`用法是這樣的:
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);
我的C#簽名是:
[DllImport(AUTODYNResultsApiDll, EntryPoint = "get_VariableInfo", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetVariableInfo(
int[] pnVariableIdArray,
IntPtr[] pcVariableName,
int[] pnUnVariableIdArray,
int[] pnVariableType);
我用它喜歡:
var stringPointers= new IntPtr[numVars];
for (int i = 0; i < numVars; i++)
{
by[i] = Marshal.AllocHGlobal(100);
}
GetVariableInfo(pnVariableIdArray, stringPointers, pnUnVariableIdArray, pnVariableType);
,然後回到字符串:
var strings = new string[numVars];
for (int i = 0; i < numVars; i++)
{
strings[i] = Marshal.PtrToStringAnsi(by[i]);
}
有沒有一種更好的方式做這個而不釋放指針的內存。只需將字符串數組作爲字符串數組複製?