Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct usage of DllImport

Suppose there is a c++ method int NativeMethod(double, double *) in a Native.dll. My first attempt at calling this method from managed code was (assuming I don't need to specify the entry point)

[DllImport("Native.dll")]
private static extern int NativeMethod(double inD, IntPtr outD);

Then to use the DLL I did

IntPtr x = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));
NativeMethod(2.0, x);

//do stuff with x

Marshal.FreeHGlobal(x);  //crash

I would like to understand why this crashes here. My first guess is that it's a heap problem due to the fact that the DLL and my application could be using a different CRT. But if that were the case why wouldn't the call to the NativeMethod crash instead? The method returned an x that I could successfully extract the double from.

I am able to get the import to work by passing the double by reference

[DllImport("Native.dll")]
private static extern int NativeMethod(double inD, IntPtr outD);

Why does the FreeHGlobal crash in the first attempt, and what is the recommended way to pass pointers to native methods? The out keyword may work fine this situation, but what if I needed to Marshal a string? I don't think I can get around AllocH and FreeH...

like image 680
insipid Avatar asked Jul 13 '10 14:07

insipid


1 Answers

I might be misunderstanding your goal, but it seems you are making it more complicated than is necessary. Just pass it by reference and let the marshalling underneath take care of it.

[DllImport("Native.dll")]
private static extern int NativeMethod(double inD, ref double outD);

double x;

x = 1;
NativeMethod( 2.0, ref x );
like image 57
Mark Wilkins Avatar answered Sep 28 '22 13:09

Mark Wilkins