gpt4 book ai didi

c++ - 通过 C#/.NET 代码编写可使用的非托管 DLL

转载 作者:行者123 更新时间:2023-11-28 08:27:40 25 4
gpt4 key购买 nike

我需要在 native 代码中实现一小部分应用程序逻辑。为了测试 PInvoke 功能,我创建了一个简单的解决方案,其中包含一个非托管 C++ Win32 Dll 和一个使用 PInvoke 使用 dll 函数的 WPF 项目。我遇到的问题是我收到关于“unbalancing the stack”和“possible signature mismatch”的异常

这是我的代码:

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 签名的调用约定和参数是否与目标非托管签名匹配。 "

我的错误在哪里?

最佳答案

已解决 :) 看来我在 C++ 函数定义中忘记了 __stdcall 关键字它应该是:__declspec(dllexport) int __stdcall add(int a, int b)

关于c++ - 通过 C#/.NET 代码编写可使用的非托管 DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3348541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com