DllImport的正确使用
假设 Native.dll 中有一个 C++ 方法 int NativeMethod(double, double *)
。我第一次尝试从托管代码调用此方法(假设我不需要指定入口点),
[DllImport("Native.dll")]
private static extern int NativeMethod(double inD, IntPtr outD);
然后使用我所做的 DLL,
IntPtr x = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));
NativeMethod(2.0, x);
//do stuff with x
Marshal.FreeHGlobal(x); //crash
我想了解为什么会在这里崩溃。我的第一个猜测是,这是一个堆问题,因为 DLL 和我的应用程序可能使用不同的 CRT。但如果是这样的话,为什么对 NativeMethod 的调用不会崩溃呢?该方法返回一个 x,我可以成功地从中提取双精度值。
我可以通过引用传递 double 来使导入工作。
[DllImport("Native.dll")]
private static extern int NativeMethod(double inD, IntPtr outD);
为什么 FreeHGlobal 在第一次尝试时会崩溃,以及将指针传递给本机方法的推荐方法是什么? out 关键字在这种情况下可能工作得很好,但如果我需要封送一个字符串怎么办?我认为我无法绕过 AllocH 和 FreeH...
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我可能误解了你的目标,但你似乎让它变得比必要的更复杂。只需通过引用传递它,然后让下面的编组处理它即可。
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.
问题是该方法采用一个 double* ,它是一个指向 double 的指针。您正在传递一个指向
IntPtr
的指针。这一点很重要,因为double
(8 字节)和IntPtr
之间存在大小差异,后者是可变大小的(4 或 8 字节)。您需要将指针分配给double
The problem is that the method takes a
double*
which is a pointer to a double. You are passing in a pointer which is pointing to anIntPtr
. This is important only in that there is a size difference betweendouble
(8 bytes) andIntPtr
which is variable sized (either 4 or 8 bytes). You need to allocate the pointer to adouble
我不是专家,但不应该是:
I am not an expert, but shouldn't it be: