网上的方法众多,但我觉得都不够清楚、简洁,用的不多,但每次都要看好几篇帖子才能搞定。
1.打开VS,创建 C++ “Win32控制台应用程序”
2.选择DLL和空项目
3.添加MyFunctions.cpp,在MyFunctions.cpp中添加一个导出函数 Add
extern "C" _declspec(dllexport) int __stdcall Add(int a, int b) { return a + b; }
4.编译生成 MyDLL.dll
5.创建一个C# 控制台应用程序(用来调用刚才的动态链接库),把生成的dll拷贝到应用程序输出目录,在Program.cs中调用代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace ConsoleApplication1 { class Program { [DllImport(@"MyDLL.dll")] private static extern int Add(int a, int b); static void Main(string[] args) { var c = Add(1, 1); } } }
搞定。
原文:https://www.cnblogs.com/nanfei/p/13331093.html