1 新建C#控制台项目CPPDLLDemo
2 在该项目中新建C++动态链接库项目
3 修改dllmain.cpp
// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
extern "C" _declspec(dllexport)int Add(int a, int b)
{
return a + b;
}
extern "C" _declspec(dllexport)int Sub(int a, int b)
{
return a - b;
}
4 编译dll项目,在解决方案下面的Debug下面可以发现CPPDLL.dll
5 编译C#项目后,将上面生成的dll拷贝进入C#项目的Debug目录
6 修改Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace CppDLLDemo
{
class Program
{
[DllImport("CPPDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int a, int b);
[DllImport("CPPDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int Sub(int a, int b);
static void Main(string[] args)
{
int result = Add(1, 2);
Console.WriteLine(result.ToString());
result = Sub(5, 4);
Console.WriteLine(result.ToString());
Console.ReadLine();
}
}
}
7 run即可