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)]