我花了一天的时间编写需要在 C# 中运行的 C++ 代码。我经历了这个 DLL tutorial在我的 C# 应用程序中使用它时遇到了问题。我将在下面发布所有代码。
我收到此 PInvokeStackImbalance 错误:'对 PInvoke 函数 'frmVideo::Add' 的调用使堆栈不平衡。这可能是因为托管 PInvoke 签名与非托管目标签名不匹配。检查 PInvoke 签名的调用约定和参数是否与目标非托管签名匹配。'
一如既往的感谢, 凯文
DLL教程.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 );
选择这两个选项中的哪一个取决于您,但出于显而易见的原因,请确保您只更改界面的一侧而不是两侧!
关于c# - 这个简单的 C++ DLL 在 C# 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10708782/