在利用C++创建一个dll项目后编译生成dll后,拷贝到已建好的C#程序中准备调用时,会出现这样那样的问题。由于我是刚上手不太了解,第一次用时,按照网上的一些方法写了一个测试代码,C++的代码如下
MyDLL.cpp
#include "stdafx.h"
extern "C" __declspec(dllexport) int ADD(int a, int b)
{
return a + b;
}
编译生成相应的DLL
在C#中进行调用,代码如下
CPPDll类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace DllTest
{
class CPPDll
{
[DllImport("MyDll.dll"]
public static extern int ADD(int x, int y);
}
}
private void button2_Click(object sender, EventArgs e)
{
int result = CPPDll.ADD(10, 20);
MessageBox.Show(Convert.ToString(result));
}
然后开始运行,此时C#默认的.Net为4.0 Client Profile ,运行过程中出现如下错误
然后将C#的.Net修改为3.5在运行则顺利成功
然后我就到网上查了一下为什么会出现这种问题,后来参考http://blog.sina.com.cn/s/blog_48cc2a81010167pm.html这篇文章里的一些方法将CPPDll中的代码修改为
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace DllTest
{
class CPPDll
{
[DllImport("MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int ADD(int x, int y);
}
}
即在 DllImport加了参数 CallingConvention = CallingConvention.Cdecl然后再运行就可以了。但是其中具体什么原因就不是很清楚了,希望有高手给解释一下其中的缘由啊!