在 C# 中导入 Visual c++ DLL 时的非托管签名



我有一个用Visual C++开发的DLL,我已经开始使用DllImport将其功能导入到c#项目中。我已经实现了一些方法,它们运行良好。

对于该特定方法,我收到以下错误:

Additional information: A call to PInvoke function 'SdkTest!SdkTest.Program::CLIENT_RealPlay' 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.

我尝试实现的 c++ 方法具有以下签名:

CLIENT_NET_API LLONG CALL_METHOD CLIENT_RealPlay(LLONG lLoginID, int nChannelID, HWND hWnd);

具有以下定义:

#define CLIENT_NET_API  __declspec(dllimport)
#define CALL_METHOD     __stdcall
#define LLONG   LONG

我的 c# 影响如下:

[DllImport("dhnetsdk.dll")]
public static extern long CLIENT_RealPlay(long lLoginID, int nChannelID, IntPtr hWnd);

(我读过 C# 中的HWND等价物是 IntPtr ,但我也尝试放置 int、long、object ...

我还尝试通过以下方式做DllImport(正如一些帖子中所建议的,并为我正在使用的其他一些方法工作(:

[DllImport("dhnetsdk.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]

无论我尝试什么,我都会遇到相同的错误。我错过了什么理解?如果引发 c++ 代码中的内部异常,我将在代码中得到哪种异常?

#define LLONG   LONG

现在,LONG映射到 long ,这是 Windows 上的有符号 32 位类型。因此,在 C# 代码中使用 long 是错误的,因为 C# long 是 64 位类型。您需要改用int。喜欢这个:

[DllImport("dhnetsdk.dll")]
public static extern int CLIENT_RealPlay(int lLoginID, int nChannelID, IntPtr hWnd);
<</div> div class="one_answers">

c++ 函数是用调用约定 stdcall 声明的,但你用 cdecl 调用它。

根据我的经验,调用堆栈损坏主要是由使用错误的调用约定引起的。

最新更新