本文将介绍C++ 中通过DLL 来调用C# 代码。
首先建立C# 的“类库”工程CShapeDLL 。
然后输入如下代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CShapeDLL { public class CMyAddClass { private int m_nNumber1; private int m_nNumber2; public int Number1 { set { m_nNumber1 = value; } get { return m_nNumber1; } } public int Number2 { set { m_nNumber2 = value; } get { return m_nNumber2; } } public int AddFunc() { return m_nNumber1 + m_nNumber2; } } public class CMyWriteLine { private string m_strText; public string Text { set { m_strText = value; } get { return Text; } } public void WriteLineFunc() { Console.WriteLine(m_strText); } } }
这里有两个类,一个是MyAddClass 类,是用来做加法运算的,另一个是CMyWriteLine ,用来输出文本的。
然后以C++ 控制台程序为例,C++ 代码如下:
#using "CShapeDLL\\CShapeDLL\\bin\\Debug\\CShapeDLL.dll" #include <stdio.h> #include <conio.h> using namespace CShapeDLL; int main() { printf(" C++通过DLL调用C#代码\n" ); printf(" - By MoreWindows( http://blog.csdn.net/morewindows/article/details/8678431 ) -\n\n" ); CMyWriteLine ^ writeLineClass = gcnew CMyWriteLine; writeLineClass->Text = "使用C# 的CMyWriteLine示范" ; writeLineClass->WriteLineFunc(); writeLineClass->Text = "By MoreWindows (http://blog.csdn.com/MoreWindows)" ; writeLineClass->WriteLineFunc(); writeLineClass->Text = "http://blog.csdn.net/morewindows/article/details/8678431" ; writeLineClass->WriteLineFunc(); printf("\n ---------------------------------- \n" ); CMyAddClass ^ addClass = gcnew CMyAddClass; addClass->Number1 = 3; addClass->Number2 = 5; printf("使用C# 的CMyAddClass示范\n" ); printf("%d + %d = %d\n" , addClass->Number1, addClass->Number2, addClass->AddFunc()); getch(); return 0; }
编译,出错。提示如下:
fatal error C1190: 托管目标代码需要“/clr”选项
好吧,修改下,在“属性”-> “配置属性”-> “常规”-> “公共语言运行库支持”中选取“公共语言运行库支持(/clr) ”
再编译,又出错!提示如下:
1>正在编译...
1>cl: 命令行error D8016 :“/MTd”和“/clr”命令行选项不兼容
1>项目: error PRJ0002 : 错误的结果2 (从“e:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.exe”返回)。
好吧,再修改下,“属性”-> “配置属性”-> “C/C++ ”-> “代码生成”-> “运行时库”中选取“多线程DLL (/MD) ”。
如果出现现下问题
1>------ 已启动生成: 项目: test, 配置: Debug Win32 ------
1>正在编译...
1>win321.cpp
1>e:\vs2005\vc\atlmfc\include\afx.h(24) : fatal error C1189: #error : Building MFC application with /MD[d] (CRT dll version) requires MFC shared dll version. Please #define _AFXDLL or do not use /MD[d]
解决方法:右击项目-->属性-->配置属性-->常规,然后在右边的“项目默认值”中的“MFC的使用”选项中选择“在共享 DLL 中使用 MFC”
再编译,成功了。运行下,又出错了——“应用程序发生异常未知的软件异常 (0xe0434f4d) ,位置为 0x7c812fd3 “。
这个怎么解决了,很简单,这是因为 EXE 程序没能加载到 DLL 文件导致的,将 CShapeDLL.dll 拷贝到 EXE 程序所在目录下,再运行,成功了。结果如下图所示(WinXP及Win7均可以运行):