1、打开Visual Studio,新建一个C#的Class Library项目(这里选择的是.Net Framework 4),项目名为CSharpDll。

2、由于默认没有引入Forms等UI库,先在reference中添加引用System.Windows.Forms以便可以在测试中使用MessageBox等。

3、最终C#编写的dll的源代码如下图所示,命名空间为CSharpDll,公共类为CSharpClass。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CSharpDll
{
public class CSharpClass
{
public CSharpClass() { }
public int add(int a , int b)
{
return a + b;
}
public void substract( int a , int b , ref int c)
{
c = a - b;
}
public static void showBox(string str)
{
MessageBox.Show("C#:" + str);
}
}
}
里面包含一个加法add,一个减法substract(为了测试指针,所以在减法的返回类型是void,而把计算结果通过ref参数c给返回),一个showBox方法(里面采用C#的MessageBox对话框显示用户输入的参数字串)
4、对project进行release build,在release目录下生成了CSharpDll.dll(待会用到)。
5、关闭CSharpDll项目,另外新建一个C++ CLR类型的Class Library项目(选择与C#项目相同的.Net Framework 4),项目名称为CppDll。

一开始我用的VS2019,发现VS2019好像无法新建 C++ CLR类型的Class Library项目了,所以学习微软的技术一定要小心,学习主流的支持很久的技术,尽量不要学习新出的技术,如果必须学新技术,一定要认真考量,一些边缘化的技术一定不要学习,没准哪天微软就不维护了。
6、选择Project->CppDll Properties…,在弹出的属性页面选择“Add New Reference..”,点击“browsing.”后选择CSharpDll项目中release目录下的CSharpDll.dll。

7、选择CSharpDll.dll后,可以看到在项目属性的References中出现了CSharpDll这个Library。
8、在CppDll项目中的CppDll.h中利用 _declspec(dllexport)导出对应的3个接口函数add,substract,showBox 。需要using namespace System::Reflection,对于这里的showBox,其参数不能采用CSharpDll里面的showBox参数的String类型,而是使用const char* 类型。
主要代码如下所示:
// CppDll.h
#pragma once
using namespace System;
using namespace System::Reflection;
__declspec(dllexport) int add(int a, int b)
{
CSharpDll::CSharpClass obj;
return obj.add(a, b);
}
__declspec(dllexport) void substract(int a, int b, int *c)
{
CSharpDll::CSharpClass obj;
obj.substract(a, b, *c);
}
__declspec(dllexport) void showBox(const char* content)
{
CSharpDll::CSharpClass obj;
String^ str = gcnew String(content);
obj.showBox(str);
}
namespace CppDll {
public ref class Class1
{
// TODO: 在此处添加此类的方法。
};
}










