我花了一天的时间来研究我需要在C#中运行的C ++代码。我遇到了这个DLL tutorial,在我的C#应用程序中使用它时遇到了麻烦。我将在下面发布所有代码。
我收到此PInvokeStackImbalance错误:'对PInvoke函数'frmVideo :: Add'的调用已使堆栈不平衡。这可能是因为托管PInvoke签名与非托管目标签名不匹配。检查PInvoke签名的调用约定和参数是否与目标非托管签名匹配。
一如既往的感谢
凯文
DLLTutorial.h
#ifndef _DLL_TUTORIAL_H_
#define _DLL_TUTORIAL_H_
#include <iostream>
#if defined DLL_EXPORT
#define DECLDIR __declspec(dllexport)
#else
#define DECLDIR __declspec(dllimport)
#endif
extern "C"
{
DECLDIR int Add( int a, int b );
DECLDIR void Function( void );
}
#endif
DLLTutorial.cpp
#include <iostream>
#define DLL_EXPORT
#include "DLLTutorial.h"
extern "C"
{
DECLDIR int Add( int a, int b )
{
return( a + b );
}
DECLDIR void Function( void )
{
std::cout << "DLL Called!" << std::endl;
}
}
使用DLL的C#代码:
using System.Runtime.InteropServices;
[DllImport(@"C:\Users\kpenner\Desktop\DllTutorialProj.dll"]
public static extern int Add(int x, int y);
int x = 5;
int y = 10;
int z = Add(x, y);
最佳答案
您的C ++代码使用cdecl
调用约定,并且C#代码默认为stdcall
。此不匹配说明了您看到的消息。
使接口的两侧匹配:
[DllImport(@"...", CallingConvention=CallingConvention.Cdecl]
public static extern int Add(int x, int y);
或者,您可以将
stdcall
用于C ++导出:DECLDIR __stdcall int Add( int a, int b );
由您决定选择这两个选项中的哪一个,但是出于明显的原因,请确保仅更改界面的一侧而不更改两者。