微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为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 __stdcall Try(int v)
  {
    return 10 + v;
  }
}

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


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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐