设为首页 加入收藏

TOP

25.2.4 混合使用C#与C++
2013-10-07 15:37:40 来源: 作者: 【 】 浏览:89
Tags:25.2.4 混合 使用

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:

  1. #include <iostream> 
  2. using namespace std;  
  3. extern "C"  
  4. {  
  5. __declspec(dllexport) int FunctionInDLL(const wchar_t* p)  
  6. {  
  7. wcout << L"The following string was received by C++(www.cppentry.com):\n '";  
  8. wcout << p << L"'" << endl;  
  9. return 42; // Return some value...  
  10. }  
  11. }  
  12.  
  13. 代码取自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的名称空间:

  1. using System.Runtime.InteropServices; 

接下来,定义函数原型,并告诉C#在哪里可以找到这个函数的实现。这是通过下面这行代码实现的,假设已经将这个库编译为HellpCpp.dll:
  1. [DllImport("HelloCpp.dll", CharSetCharSet = CharSet.Unicode)]  
  2. public static extern int FunctionInDLL(String s); 

这行的第一部分表示C#应该从一个名为HelloCpp.dll的库导入这个函数,而且应该使用Unicode字符串。第二部分说明了这个函数的实际原型,表示这是一个接受一个字符串作为参数并返回一个整数的函数。下面的代码展示了如何在C#中使用C++(www.cppentry.com)库的完整例子:
  1. using System;  
  2. using System.Runtime.InteropServices;  
  3. namespace HelloCSharp  
  4. {  
  5. class Program  
  6. {  
  7. [DllImport("HelloCpp.dll", CharSetCharSet = CharSet.Unicode)]  
  8. public static extern int FunctionInDLL(String s);  
  9. static void Main(string[] args)  
  10. {  
  11. Console.WriteLine("Writen by C#.");  
  12. int res = FunctionInDLL("Some string from C#.");  
  13. Console.WriteLine("C++(www.cppentry.com) returned the value " + res);  
  14. }  
  15. }  
  16. }  
  17.  
  18. 代码取自CSharp\HelloCSharp.cs  

输出如下所示:
  1. Writen by C#.  
  2. The following string was received by C++(www.cppentry.com):  
  3. 'Some string from C#.'  
  4. C++(www.cppentry.com) returned the value 42  

这段C#代码的细节已经超出了这本C++(www.cppentry.com)书的范围,不过通过这个例子应该了解了总体思路。
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇4.1.1 程序说明 下一篇25.3 本章小结

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·C语言中如何将结构体 (2025-12-24 22:20:09)
·纯C语言结构体成员变 (2025-12-24 22:20:06)
·C语言中,指针函数和 (2025-12-24 22:20:03)
·哈希表 - 菜鸟教程 (2025-12-24 20:18:55)
·MySQL存储引擎InnoDB (2025-12-24 20:18:53)