c# - 为 C# 制作 C++ DLL

标签 c# c++ dll

我制作了一个非常简单的 Dll,如下所示:

extern "C"
{
  __declspec(dllexport) int Try(int v)
  {
    return 10 + v;
  }
}

然后我想在我的 C# 应用程序中使用它:

class Program
{
    [DllImport("TestLib.dll")]
    public static extern int Try(int v);

    static void Main(string[] args)
    {
        Console.WriteLine("Wynik: " + Try(20));
        Console.ReadLine();
    }
}

在我尝试传递参数之前,它一直在工作。现在我在运行时出现以下错误:

A call to PInvoke function 'ConsoleApplication2!ConsoleApplication1.Program::Try' has unbalanced the stack. 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.

不知道哪里出了问题。

最佳答案

您收到的错误消息确实包含一个很好的建议:

Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

您应该在两侧(C++ dll 和 C# 程序集)指定相同的调用约定。在 C++ 中,您可以通过在函数声明前加上 __cdecl、__stdcall 等之一来指定它。


extern "C"
{
  __declspec(dllexport) int <strong>__stdcall</strong> Try(int v)
  {
    return 10 + v;
  }
}

在 C# 端,您使用 DllImport 属性指定它,默认的是 CallingConvention.StdCall,它对应于 C++ 中的 __stdcall,因此,看起来您在 C++ 端有一个 __cdecl。要解决此问题,请在 DLL 中使用 __stdcall,如上所示,或在 C# 中使用 CDecl,如下所示:


class Program
{
    [DllImport("TestLib.dll", <strong>CallingConvention=CallingConvention.Cdecl</strong>)]
    public static extern int Try(int v);

    static void Main(string[] args)
    {
        Console.WriteLine("Wynik: " + Try(20));
        Console.ReadLine();
    }
}

关于c# - 为 C# 制作 C++ DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7666144/

相关文章:

c# - Observable.Interval 对高频事件有用吗?

c# - 如何正确地将 View 控件绑定(bind)到 ViewModel 列表(WPF MVVM)

python - 如何使用 swig C++ 命名空间作为 python 模块公开

windows - 在 Windows 安装项目中注册和注销 DLL

python ctypes 抛出错误?

c++ - 跨 DLL 边界的安全字符串复制

c# - 是否可以使用 Lambda 表达式格式化查询结果?

c# - 使用多个角色提供者授权属性

c++ - 使用 boost 序列化到磁盘后无法加载回数据

java - 在哈希表中创建字符串的哈希值的时间复杂度