I have a thirdparty c++ method in a dll like this:
void GetValues(int *pCount, int **ppValues);
c++ usage would be:
int count = 0, *pValues = NULL;
GetValues(&count, &pValues);
CoTaskMemFree(pValues);
I want to call this method in c#: it is declared as :
void GetValues([out] int pCount, IntPtr ppValues);
c# usage (the method using this code is marked as unsafe):
int *pValues = null;
try
{
int count;
GetValues(out count, new IntPtr(&pValues));
for (var i=0; i<count; i++)
{
var val = pValues[i];
}
}
finally
{
Marshal.FreeCoTaskMem(new IntPtr(pValues));
}
this seems to work. But I'm wondering if this is correct or if there are problems with this approach I didin't see.
EDIT: changed c# declaration from void GetValues([out] int pCount, [out] IntPtr ppValues); to void GetValues([out] int pCount, IntPtr ppValues);
Maybe I am missing something, but "out" prefix is missing in call GetValues(out count, new IntPtr(&pValues));
I would solve this problem simpler:
unsafe void test()
{
IntPtr intPtr = IntPtr.Zero;
try
{
int count = 0;
GetValues(out count, out intPtr);
int* pValues = (int*)intPtr;
for (var i = 0; i < count; i++)
{
var val = pValues[i];
}
}
finally
{
Marshal.FreeCoTaskMem(intPtr);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.