这个简单的C ++ DLL不能在C# [英] This simple C++ DLL is not working in C#

查看:167
本文介绍了这个简单的C ++ DLL不能在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在花费一天的时间来处理c ++代码,我需要在c#中运行。我浏览了这个 DLL教程,并在我的c#应用程序中遇到麻烦。我将发布以下所有代码。

I have been spending the day working on come c++ code that I need to run in c#. I ran through this DLL tutorial and have been having trouble using it in my c# app. I will post all the code below.

我得到这个 PInvokeStackImbalance 错误:'调用PInvoke函数'frmVideo :: Add'有堆栈不平衡这可能是因为托管的PInvoke签名与非托管目标签名不匹配。检查PInvoke签名的调用约定和参数是否与目标非托管签名相匹配。

I am getting this PInvokeStackImbalance error: 'A call to PInvoke function 'frmVideo::Add' 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.'

一如既往地感谢
Kevin

Thanks as always, Kevin

#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



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#代码:



C# code to use the DLL:

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 。这个不匹配解释了你看到的消息。

You C++ code uses the cdecl calling convention and the C# code defaults to stdcall. This mismatch explains the message that you see.

使界面的两边匹配:

[DllImport(@"...", CallingConvention=CallingConvention.Cdecl]
public static extern int Add(int x, int y);

或者您可以使用 stdcall 作为您的C ++导出: / p>

Alternatively you could use stdcall for your C++ exports:

DECLDIR __stdcall int Add( int a, int b );

由您选择的这两个选项中的哪一个,但请确保您只更改界面的一侧,而不是两者都是显而易见的原因!

It's up to you which of these two options you choose, but make sure that you only change one side of the interface and not both, for obvious reasons!

这篇关于这个简单的C ++ DLL不能在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆