我尝试在我的 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 异常。 你能帮我一下吗?
最佳答案
这种不平衡可能是由于调用约定(cdecl
与 stdcall
)不匹配或函数参数大小和类型不匹配造成的。
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/