使用 P/Invoke 编组双参数
我尝试执行的 P/Invoke 调用遇到问题。我必须从 C# 程序调用 C++ 类。我有这个类的源代码,所以我所做的就是将它放入一个 DLL 项目中,并创建导出函数来访问它的 main 方法。这应该足以满足我的需要并让事情变得简单。
我的导出方法如下所示:
extern "C" _declspec(dllexport) void Inference(double *c1, double *c2, double *c3, double *result)
{
/* somecode */
}
编译后,我可以在 dumpbin
输出中看到导出。
现在的问题是,我无法从 C# 代码中调用此方法,因为我总是收到 PInvokeStackInbalance
异常,告诉我
这可能是因为托管 PInvoke 签名与 非托管目标签名。
我尝试用这个调用该方法:
[DllImport("InferenceEngine.dll")]
extern static unsafe void Inference(double *c1, double *c2, double *c3, double *result);
我也尝试过这个:
[DllImport("InferenceEngine.dll")]
extern static void Inference(ref double c1, ref double c2, ref double c3, ref double result);
...这都是 MSDN 上记录的可能方法,但没有运气。有谁知道问题是什么?
谢谢 !
I have a problem with a P/Invoke call I'm trying to do. I have to call a C++ class from a C# program. I have the source of this class so what I did is put it in a DLL project and create export functions to access it's main method. That should be enough to do what I need and keep things simple.
My export method looks like this :
extern "C" _declspec(dllexport) void Inference(double *c1, double *c2, double *c3, double *result)
{
/* somecode */
}
This compiles, and I can see the export in a dumpbin
output.
Now the problem is, I can't call this method from my C# code because I always get a PInvokeStackInbalance
exception, telling me that
This is likely because the managed
PInvoke signature does not match the
unmanaged target signature.
I tried calling the method with this :
[DllImport("InferenceEngine.dll")]
extern static unsafe void Inference(double *c1, double *c2, double *c3, double *result);
I also tried this :
[DllImport("InferenceEngine.dll")]
extern static void Inference(ref double c1, ref double c2, ref double c3, ref double result);
... which were both possible ways documented on MSDN but with no luck. Does anyone have any clue about what the problem is ?
Thanks !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该将 C++ 函数声明为
__stdcall
,这是 P/Invoke 默认值:也可以单独保留 C++ 原型并更改 P/Invoke 声明:
cdecl
是不经常与 P/Invoke 一起使用,可能是因为 Windows API 是stdcall
。You should declare your C++ function as
__stdcall
, which is the P/Invoke default:It's also possible to leave the C++ prototype alone and change the P/Invoke declaration:
cdecl
isn't used often with P/Invoke, probably because the Windows API isstdcall
.