gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:06:32 25 4
gpt4 key购买 nike

我制作了一个非常简单的 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/

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