问题描述
我尝试在我的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 异常。 你能帮我吗?
解决方法
验证您的通话惯例;请注意,extern "C"
默认为CallingConvention.Cdecl
。此错误通常是由错误的调用约定引起的。
还要注意,C#的long
和C ++的long
可能会有所不同。
您似乎正在尝试指定__stdcall
,但这是语法错误。无论如何,请确保您的呼叫约定已同步。
这种不平衡可能是由于大小和类型不匹配的调用约定(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));
}
}
}