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...