使用 P/Invoke 编组双参数

发布于 2024-10-05 21:09:29 字数 894 浏览 4 评论 0原文

我尝试执行的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

玩心态 2024-10-12 21:09:29

您应该将 C++ 函数声明为 __stdcall,这是 P/Invoke 默认值:

extern "C" _declspec(dllexport) void __stdcall Inference(double *c1, double *c2, double *c3, double *result);

也可以单独保留 C++ 原型并更改 P/Invoke 声明:

[DllImport("InferenceEngine.dll", CallingConvention=CallingConvention.Cdecl)]

cdecl 是不经常与 P/Invoke 一起使用,可能是因为 Windows API 是 stdcall

You should declare your C++ function as __stdcall, which is the P/Invoke default:

extern "C" _declspec(dllexport) void __stdcall Inference(double *c1, double *c2, double *c3, double *result);

It's also possible to leave the C++ prototype alone and change the P/Invoke declaration:

[DllImport("InferenceEngine.dll", CallingConvention=CallingConvention.Cdecl)]

cdecl isn't used often with P/Invoke, probably because the Windows API is stdcall.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文