25.2.4 混合使用C#与C++(www.cppentry.com)
尽管这是一本C++(www.cppentry.com)的书,但是我们不会假装没有更新更时髦的语言。C#是一个例子。通过使用C#中的Interop服务,在C#应用程序中调用C++(www.cppentry.com)代码非常容易。一个示例场景可能是您正在用C#开发应用程序的一部分,例如图形用户界面,但是用C++(www.cppentry.com)实现一些性能关键的组件。为了使得Interop工作,您需要用C++(www.cppentry.com)编写一个库,然后在C#中调用这个库。在Windows上,这个库在.DLL文件中。下面的C++(www.cppentry.com)例子定义了一个FunctionInDLL()函数,这个函数将被编译成库。该函数接受一个Unicode字符串,并返回一个整数。这个实现将接收到的字符串写入控制台,并向调用者返回值42:
- #include <iostream>
- using namespace std;
- extern "C"
- {
- __declspec(dllexport) int FunctionInDLL(const wchar_t* p)
- {
- wcout << L"The following string was received by C++(www.cppentry.com):\n '";
- wcout << p << L"'" << endl;
- return 42; // Return some value...
- }
- }
-
- 代码取自CSharp\HelloCpp.cpp
请记住,您正在实现一个库中的函数,而不是在编写一个程序,所以不需要一个main()函数。这段代码的编译取决于您的环境。如果您正在使用Microsoft Visual C++(www.cppentry.com),需要进入项目属性,然后选择Dynamic Library (.dll)作为配置类型。请注意,这个例子通过__declspec(dllexport)告诉链接器这个函数应该让库的客户使用。具体的实现取决于您的编译器。 __declspec(dllexport)的方式是Microsoft Visual C++(www.cppentry.com)使用的方式。
有了这个库之后,就可以在C#中通过Interop服务进行调用。首先,需要包含Interop的名称空间:
- using System.Runtime.InteropServices;
接下来,定义函数原型,并告诉C#在哪里可以找到这个函数的实现。这是通过下面这行代码实现的,假设已经将这个库编译为HellpCpp.dll: - [DllImport("HelloCpp.dll", CharSetCharSet = CharSet.Unicode)]
- public static extern int FunctionInDLL(String s);
这行的第一部分表示C#应该从一个名为HelloCpp.dll的库导入这个函数,而且应该使用Unicode字符串。第二部分说明了这个函数的实际原型,表示这是一个接受一个字符串作为参数并返回一个整数的函数。下面的代码展示了如何在C#中使用C++(www.cppentry.com)库的完整例子:- using System;
- using System.Runtime.InteropServices;
- namespace HelloCSharp
- {
- class Program
- {
- [DllImport("HelloCpp.dll", CharSetCharSet = CharSet.Unicode)]
- public static extern int FunctionInDLL(String s);
- static void Main(string[] args)
- {
- Console.WriteLine("Writen by C#.");
- int res = FunctionInDLL("Some string from C#.");
- Console.WriteLine("C++(www.cppentry.com) returned the value " + res);
- }
- }
- }
-
- 代码取自CSharp\HelloCSharp.cs
输出如下所示:- Writen by C#.
- The following string was received by C++(www.cppentry.com):
- 'Some string from C#.'
- C++(www.cppentry.com) returned the value 42
这段C#代码的细节已经超出了这本C++(www.cppentry.com)书的范围,不过通过这个例子应该了解了总体思路。