自己实践了一下,其实不是很难,怕自己忘记掉,再加上有几个需要注意的问题,这里记录下来。
1. c# 创建dll library
using System; using System.Collections.Generic; using System.Text; namespace AddDll { public class Add { public int iadd(int a, int b) { int c = a + b; return c; } } }
2. c++实现调用程序
这里创建一个Win32的控制台应用程序
Configure:右键点击解决方案资源管理器中的UseDll,选择“属性”,将公共语言运行库支持设置为“公共语言运行库支持(/clr)” 即Common Language Runtime Support (/clr)
PS:如果你是建立一个MFC程序的话,必须把Use of MFC设置成:Use MFC in a Shared DLL 共享dll,不然会引起冲突
(error D8016: '/clr' and '/MTd' command-line options are incompatible 错误)
#include "stdio.h" #using "..\debug\AddDll.dll" using namespace AddDll; int main(){ int result; Add ^add = gcnew Add(); //生成托管类型 //gcnew creates an instance of a managed type (reference or value type) on the garbage //collected heap. The result of the evaluation of a gcnew expression is a handle (^) to //the type being created. result = add->iadd(10,90); printf("%d",result); scanf("%s"); return 0; }
Attention:
1. 使用#using引用dll,而不是#inculde。
2. 别忘了using namespace CSLib
3. 使用C++/clr语法,采用正确的访问托管对象,即:使用帽子‘^’,而不是星星‘*’。