c# - 将 C++ DLL 导入 C#

标签 c# c++ dll dllimport

我尝试在我的 C# 项目中实现 C++ DLL。我给出了以下头文件:

#ifdef EBEXPORT
const long EBDECL
#else
const long EBDECL __declspec(dllimport)
#endif

const long EBCALL __stdcall


#if defined (__cplusplus)
extern "C" 
{
#endif

EBDECL long EBCALL EbInitTcp(long nUnit, const char* pIP, long nIPSize);

#if defined (__cplusplus)
}
#endif

这是我用 C# 实现 DLL 的代码:

using System.Runtime.InteropServices;

namespace NoName
{
    class DLLImport
    {
        [DllImport("C:/lib/host.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public static extern long EbInitTcp(long nUnit, string pIP, long nIPSize);

        public void Init()
        {
            string ip = "192.168.0.1";
            EbInitTcp(1, ip, ip.Length));
        }

    }
}

如果我执行代码,我会收到 PInvokeStackImbalance 异常。 你能帮我一下吗?

最佳答案

这种不平衡可能是由于调用约定(cdeclstdcall)不匹配或函数参数大小和类型不匹配造成的。

C++ 调用约定定义并不罕见,它通常使用 #define 进行定义。

#ifdef EBEXPORT
  #define EBDECL __declspec(dllexport)
#else
  #define EBDECL __declspec(dllimport)
#endif

#define EBCALL __stdcall

#if defined (__cplusplus)
extern "C" 
{
#endif

EBDECL const long EBCALL EbInitTcp(long nUnit, const char* pIP, long nIPSize);

#if defined (__cplusplus)
}
#endif

在 C# 方面;

using System.Runtime.InteropServices;

namespace NoName
{
    class DLLImport
    {
        [DllImport("C:/lib/host.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public static extern long EbInitTcp(int nUnit, string pIP, int nIPSize);

        public void Init()
        {
            string ip = "192.168.0.1";
            EbInitTcp(1, ip, ip.Length));
        }

    }
}

关于c# - 将 C++ DLL 导入 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64221358/

相关文章:

windows - 如何使用序号调用导出函数

c# - 无法修改存储在另一个属性中的结构的属性

c# - 调用 web 服务 webmethod 抛出 HTTP/1.1 404 Not Found

c++ - 从kinect v2获取颜色框架

c++ - 在VS2013中使用initializer_list对函数的不明确调用

debugging - 如何调试 DLL 加载失败 : Invalid access to memory location

c# - 如何从 Windows 应用商店应用程序中的 SecondaryTile 导航到特定页面?

c# - 从其他 C# 服务器端 Controller 调用 ASP.NET post 路由

c++ - 如何修复QT中的GL.h编译错误?

c# - 为什么我的 .dll 试图加载 mscorlib.dll?