通过 C#/.NET 代码编写非托管 DLL 消耗品
我需要用本机代码实现一小部分应用程序逻辑。 为了测试 PInvoke 功能,我使用非托管 C++ Win32 Dll 和一个使用 PInvoke 使用 dll 函数的 WPF 项目创建了一个简单的解决方案。 我遇到的问题是我收到有关“堆栈不平衡”和“可能的签名不匹配”的异常
这是我的代码:
1) C++ (dll)
#include <stdio.h>
#include <Windows.h>
extern "C"
{
__declspec(dllexport) int add(int a, int b)
{
return a+b;
}
}
2) C#:
public partial class MainWindow : Window
{
[DllImport("MyLibrary.dll")]
static extern int add(int a, int b);
public MainWindow()
{
InitializeComponent();
}
private void btnVersion_Click(object sender, RoutedEventArgs e)
{
var res = add(3,2);
}
}
代码抛出一个异常,指出“这很可能”因为托管 PInvoke 签名与非托管目标签名不匹配。请检查 PInvoke 签名的调用约定和参数是否与目标非托管签名匹配。”
我的错误在哪里?
I need to implement a small part of my application logic in native code.
To test PInvoke capabilities I created a simple solution with an unmanaged C++ Win32 Dll and a WPF project that consumes the dll functions using PInvoke.
The problem I run into is that i receive exception about "unbalancing the stack" and "possible signature mismatch"
Here is my code:
1) C++ (dll)
#include <stdio.h>
#include <Windows.h>
extern "C"
{
__declspec(dllexport) int add(int a, int b)
{
return a+b;
}
}
2) C#:
public partial class MainWindow : Window
{
[DllImport("MyLibrary.dll")]
static extern int add(int a, int b);
public MainWindow()
{
InitializeComponent();
}
private void btnVersion_Click(object sender, RoutedEventArgs e)
{
var res = add(3,2);
}
}
The code throws an exception stating "This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature."
Where is my mistake?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决了:)看来我忘记了c++函数定义中的__stdcall关键字它应该是:
__declspec(dllexport) int __stdcall add(int a, int b)
solved :) it seems i forgot __stdcall keyword in c++ function definition It should have been:
__declspec(dllexport) int __stdcall add(int a, int b)
尝试对非托管函数使用此签名:
问题与 C++ 名称修饰有关。如果没有
extern "C"
,名称就会被破坏,并且 C# DLL 无法找到它。Try this signature for the unmanaged function:
THe issue was to do with C++ name mangling. Without
extern "C"
the name gets mangled and the C# DLL cannot find it.