1、首先打开vs2013(其他版本也可以),在C++项目中选择 Win32程序,然后在控制台程序或者win32程序任选一个。 写上项目名字点创建。(本例用VS2013系统默认项目名,路径随意。)
2、选“空项目”建一个计较干净的DLL程序。
3、创建项目,这样我们得到一个空项目,在这个项目中,除了几个文件加以外什么也没有,我们在文件夹上点右键,创建新项。在新项里面分别创建一个CPP文件和一个def文件。
4、在“.def”文件中添加代码:LIBRARYEXPORTSmySum在“.cpp”文件中添加代码://宏定义 #define LIBEXPORT_API extern "C" __declspec(dllexport)//设置函数 LIBEXPORT_API int __stdcall mySum(int a, int b){ return a + b;}
5、编译C++ DLL文件,找到编译好的.dll文件,并放到C#程序目录下。
6、c#创建控制台应用程序对C++ dll进行访问usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Runtime.InteropServices;namespaceConsoleApplication1{classProgram{[DllImport("Win32Project1.dll")]publicstaticexternintmySum(intx,inty);staticvoidMain(string[] args){intx = mySum(5, 9);x = x++;Console.WriteLine(x.ToString());stringy= Console.ReadLine(); }}}执行后得出正确结果:14