Calls to native dlls from C#

D

dln

Hey all. I'm a bit new to the language and I'm trying to figure out how to
have my c# application interact with native code that is exported via a dll.
I've run into a problem interfacing with a native dll method where one or
more of the parameters in the native routine is an array or pointer to block
of contiguous memory. So, for example, the method as exported from the
native Dll is declared as:

extern "C" unsigned int __stdcall GetHandles(unsigned int* handleArray,
unsigned* size);

Where "handleArray" is an array of unsigned integers and "size" is the
number of elements in the array. My c# function import statement reads:

[DllImport(DLL_NAME, CallingConvention=CallingConvention.StdCall)]
public static extern UInt32
GetHandles([MarshalAs(UnmanagedType.LPArray)] ref UInt32[] handles, ref
UInt32 size);

When I call the native method from my c# code, I can step into the native
code and the method operates exactly as I would expect it to. However, when
returning from the native code, an exception is thrown which appears to be
related to the passing of the unsigned integer array. If I remove the "ref"
specification for the array, the code is executed with no errors. However,
I see the native code filling in the array but the array returned to my c#
code is empty (so it appears to me that the memory referenced by the c#
array and the memory passed to the native routine are two different blocks
of memory). I've also tried replacing the "ref" specifier with "out", but
the same exception is thrown when returning from the native code (does "out"
and "ref" equate to the same thing in c#?).

After going through the MSDN documentation on marshalling and calling native
routines from c#, I can't say that I fully understand how I can pass arrays
(or any data buffer for that matter) back and forth between native code and
c#. Can anybody tell me where I'm going wrong?

Thanks.
 
D

dln

....I figured it out. I needed to remove the "ref" specification on the
array and add a SizeParamIndex=1 to the MarshalAs declaration. Thanks
anyway.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top