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