>>> Hi all
>>>
[quoted text clipped - 30 lines]
>
> Bjarne Nielsen
Well you have to solve two problems here:
- Unmarshal the returned buffer.
- Free the buffer.
The first one depends on how you want to access the buffer (say an array of int's), do you
want to access the native array elements directly, or do you need a managed copy of the
array.
Following is a sample for the latter, the C++ takes a aparamter that is defined as a pointer
to an int[] and a the address of an int to store the length.
//C++, error checking omitted!
extern "C" void __declspec(dllexport) __stdcall Foo(int *d[], int &size)
{
size = 100;
int *arPtr = new int[size];
*d = arPtr;
for(int n = 0; n < size; n++)
*arPtr++ = n;
}
//C#
[DllImport("somedll"), SuppressUnmanagedCodeSecurity]
static extern void Foo(out IntPtr d, out int size);
...
IntPtr ptrArray = IntPtr.Zero;
int arraySize;
GetSimpleArray(out ptrArray, out arraySize);
int[] mngdArray = new int[arraySize];
try {
Marshal.Copy(ptrArray, mngdArray, 0, arraySize);
}
finally
{
// call function to delete the unmanaged array
}
foreach(int i in mngdArray )
Console.WriteLine(i);
...
Freeing the buffer depends on the allocator used, in above sample, the new operator is used
to allocate an int[], so you 'l have to declare a function that calls delete[] of the
pointer to the array. You need to make sure you call this function whenever you have done
with the marshaling.
extern "C" void __declspec(dllexport) __stdcall DeleteArray(void *d)
{
if(d)
delete[] d;
...
}
Willy.
Bjarne Nielsen - 28 Feb 2007 10:20 GMT
>>>> Hi all
>>>>
[quoted text clipped - 85 lines]
>
> Willy.
Thank you VERY much for this detailed description. I haven't tried it yet,
but I shall get to it ASAP, and if I get get further problems, I'll get
back.
Thanks again!!
Bjarne Nielsen