1 Dll文件
//MyDll.h
extern"C" _declspec(dllexport) int addTest(int a,int b);
// MyDll.cpp: 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include "MyDll.h"
#include <iostream>
int addTest(int a,int b)
{
return a+b;
}
2 C++调用Dll
//CallMyDll.h
#ifndef _CALL_MY_DLL_
#define _CALL_MY_DLL_
#include "windows.h"
typedef int(*pAdd)(int a,int b);
HINSTANCE HDll;
#endif
// CallMyDll.cpp: 定义控制台应用程序的入口点。
#include "CallMyDll.h"
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
HDll = LoadLibrary(L"MyDll.dll");
pAdd pAddCall = (pAdd)GetProcAddress(HDll,"addTest");
int m = pAddCall(3,6);
//cout<<"m = "<<m<<endl;
printf("m = %d",m);
return 0;
}
3 C#调用dll
调试代码 ,解决方案 添加项目
/*设置:项目/右击 属性/调试/启用调试器/启用非托管代码调试*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace CsCallCDll
{
class Program
{
[DllImport(@"MyDll.dll", EntryPoint = "addTest", CallingConvention = CallingConvention.Cdecl)]
public static extern int addTest(int a, int b);
static void Main(string[] args)
{
int iTest = addTest(2,5);
Console.WriteLine("iTest = {0}",iTest);
}
}
}
问题:弹出如下提示
托管调试助手“PInvokeStackImbalance”在“D:\My Documents\Visual Studio 2008\Projects\CsCallMyDll\bin\Debug\CsCallMyCDll.exe”中检测到故障。
其他信息: 对 PInvoke 函数“CsCallMyCDll!CsCallCDll.Program::addTest”的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。请检查 PInvoke 签名的调用约定和参数与非托管的目标签名是否匹配。
[DllImport(@"MyDll.dll")]
改为:
[DllImport(@"MyDll.dll", EntryPoint = "addTest", CallingConvention = CallingConvention.Cdecl)]