Assume that in the Native.dll file there is a C ++ method int NativeMethod(double, double *) . My first attempt to call this method from managed code was (assuming I don't need to specify an 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 is happening here. My first assumption is that this is a heap problem because the DLL and my application can use a different CRT. But if so, why not call the NativeMethod call? The method returned x, from which I could successfully extract double from.
I can make the import work by passing double by reference
[DllImport("Native.dll")] private static extern int NativeMethod(double inD, IntPtr outD);
Why is FreeHGlobal crashing in the first place and what is the recommended way to pass pointers to your own methods? The out keyword might work fine in this situation, but what if I needed to marshal a string? I donβt think I can get around AllocH and FreeH ...
c # dll marshalling pinvoke unmanaged
insipid
source share