在C#中使用C++编写的类——用托管C++进行封装[转]

现在在Windows下的应用程序开发,VS.Net占据了绝大多数的份额。因此很多以前搞VC++开发的人都转向用更强大的VS.Net。在这种情况 下,有很多开发人员就面临了如何在C#中使用C++开发好的类的问题。下面就用一个完整的实例来详细说明怎样用托管C++封装一个C++类以提供给C#使 用。

比如,现在有一个工程名为NativeCppDll的由C++编写的DLL,里面输出了一个CPerson类。下面是具体的代码:

  1. // NativeCppDll.h
  2. #pragma once
  3. #ifndef LX_DLL_CLASS_EXPORTS
  4. #define LX_DLL_CLASS __declspec(dllexport)
  5. #else
  6. #define LX_DLL_CLASS __declspec(dllimport)
  7. #endif
  8. class LX_DLL_CLASS CPerson
  9. {
  10. public:
  11. CPerson();
  12. CPerson(const wchar_t *pName, const wchar_t cSex, int iAge);
  13. void SetName(const wchar_t *pName);
  14. wchar_t * GetName();
  15. void SetSex(const wchar_t cSex);
  16. wchar_t GetSex();
  17. void SetAge(int iAge);
  18. int GetAge();
  19. wchar_t * GetLastError();
  20. private:
  21. wchar_t m_szName[128];
  22. wchar_t m_cSex;
  23. int m_iAge;
  24. wchar_t m_szLastError[128];
  25. void ShowError();
  26. };
  27. // NativeCppDll.cpp
  28. #include "stdafx.h"
  29. #include "NativeCppDll.h"
  30. #include
  31. #include
  32. using namespace std;
  33. CPerson::CPerson()
  34. {
  35. wcscpy_s(m_szName, _T("No Name"));
  36. m_cSex = ‘N‘;
  37. m_iAge = 0;
  38. wcscpy_s(m_szLastError, _T("No Error"));
  39. }
  40. CPerson::CPerson(const wchar_t *pName, const wchar_t cSex, int iAge)
  41. {
  42. wcscpy_s(m_szLastError, _T("No Error"));
  43. SetName(pName);
  44. SetSex(cSex);
  45. SetAge(iAge);
  46. }
  47. void CPerson::SetName(const wchar_t *pName)
  48. {
  49. if ((pName == NULL) || (wcslen(pName) == 0) || (wcslen(pName) > 127))
  50. {
  51. wcscpy_s(m_szName, _T("No Name"));
  52. wcscpy_s(m_szLastError, _T("The length of the input name is out of range."));
  53. ShowError();
  54. return;
  55. }
  56. wcscpy_s(m_szName, pName);
  57. }
  58. wchar_t * CPerson::GetName()
  59. {
  60. return m_szName;
  61. }
  62. void CPerson::SetSex(const wchar_t cSex)
  63. {
  64. if ((cSex != ‘F‘) && (cSex != ‘M‘) && (cSex != ‘m‘) && (cSex != ‘f‘))
  65. {
  66. m_cSex = ‘N‘;
  67. wcscpy_s(m_szLastError, _T("The input sex is out of [F/M]."));
  68. ShowError();
  69. return;
  70. }
  71. m_cSex = cSex;
  72. }
  73. wchar_t CPerson::GetSex()
  74. {
  75. return m_cSex;
  76. }
  77. void CPerson::SetAge(int iAge)
  78. {
  79. if ((iAge < 0) || (iAge > 150))
  80. {
  81. m_iAge = 0;
  82. wcscpy_s(m_szLastError, _T("The input age is out of range."));
  83. ShowError();
  84. return;
  85. }
  86. m_iAge = iAge;
  87. }
  88. int CPerson::GetAge()
  89. {
  90. return m_iAge;
  91. }
  92. wchar_t * CPerson::GetLastError()
  93. {
  94. return m_szLastError;
  95. }
  96. void CPerson::ShowError()
  97. {
  98. cerr << m_szLastError << endl;
  99. }

这是一个很典型的由C++开发的DLL,输出一个完整的C++类。如果现在要求开发一个C#工程,需要用到这个DLL中输出的C++类CPerson,该
怎么办呢?针对这个例子来说,类CPerson非常小,可以用C#重新写一个跟这个C++类一样的类。可是,如果需要的C++类很大,或者很多的时候,重
写工程将非常庞大。而且这样没有对现有的代码进行重用,浪费了现有资源,开发起来费时费力。

当然,还是有方法解决这个问题的。那就是用托管C++将C++类给封装一下,然后再提供给C#来使用。下面就用代码来详细说明怎样用托管C++来封装上面的那个C++类。

首先,要创建一个托管C++的DLL工程ManageCppDll,然后在里面添加下面的代码:

  1. // ManageCppDll.h
  2. #pragma once
  3. #define LX_DLL_CLASS_EXPORTS
  4. #include "../NativeCppDll/NativeCppDll.h"
  5. using namespace System;
  6. namespace ManageCppDll
  7. {
  8. public ref class Person
  9. {
  10. // 包装所有类CPerson的公有成员函数
  11. public:
  12. Person();
  13. Person(String ^ strName, Char cSex, int iAge);
  14. ~Person();
  15. property String ^ Name
  16. {
  17. void set(String ^ strName);
  18. String ^ get();
  19. }
  20. property Char Sex
  21. {
  22. void set(Char cSex);
  23. Char get();
  24. }
  25. property int Age
  26. {
  27. void set(int iAge);
  28. int get();
  29. }
  30. String ^ GetLastError();
  31. private:
  32. // 类CPerson的指针,用来调用类CPerson的成员函数
  33. CPerson *m_pImp;
  34. };
  35. };

从这个头文件就能看出来,这是对C++类CPerson的包装。类Person的所有公有成员函数都跟C++类CPerson一样,只不过成员函数的参数
和返回值就改成了托管C++的类型,这也是让类Person能在C#中使用的首要条件。当然只需要对公有成员函数进行封装,对于保护成员函数和私有成员函
数则不必做任何封装。

类Person仅有一个私有的成员变量:一个类CPerson的指针。而类Person的所有成员函数的实现都是靠这个CPerson指针来调用类CPerson的相应成员函数来实现。

下面是具体的实现代码:

  1. // ManageCppDll.cpp
  2. #include "stdafx.h"
  3. #include "ManageCppDll.h"
  4. #include
  5. namespace ManageCppDll
  6. {
  7. // 在构造函数中创建类CPerson的对象并在析构函数中将该对象销毁
  8. // 所有的成员函数实现都是通过指针m_pImp调用类CPerson的相应成员函数实现
  9. Person::Person()
  10. {
  11. m_pImp = new CPerson();
  12. }
  13. Person::Person(String ^ strName, Char cSex, int iAge)
  14. {
  15. // 将string转换成C++能识别的指针
  16. pin_ptr<</SPAN>const wchar_t> wcName = PtrToStringChars(strName);
  17. m_pImp = new CPerson(wcName, cSex, iAge);
  18. }
  19. Person::~Person()
  20. {
  21. // 在析构函数中删除CPerson对象
  22. delete m_pImp;
  23. }
  24. void Person::Name::set(String ^ strName)
  25. {
  26. pin_ptr<</SPAN>const wchar_t> wcName = PtrToStringChars(strName);
  27. m_pImp->SetName(wcName);
  28. }
  29. String ^ Person::Name::get()
  30. {
  31. return gcnew String(m_pImp->GetName());
  32. }
  33. void Person::Sex::set(Char cSex)
  34. {
  35. m_pImp->SetSex(cSex);
  36. }
  37. Char Person::Sex::get()
  38. {
  39. return m_pImp->GetSex();
  40. }
  41. void Person::Age::set(int iAge)
  42. {
  43. m_pImp->SetAge(iAge);
  44. }
  45. int  Person::Age::get()
  46. {
  47. return m_pImp->GetAge();
  48. }
  49. String ^ Person::GetLastError()
  50. {
  51. return gcnew String(m_pImp->GetLastError());
  52. }
  53. };

如果要在C#中使用类Person,首先要添加对ManageCppDll.dll的引用,然后就可以像用普通的C#类一样的使用类Person了。比如下面这样的代码:

  1. using ManageCppDll;
  2. Person person = new Person();
  3. person.Name = "StarLee";
  4. person.Sex = ‘M‘;
  5. person.Age = 28;

熟悉设计模式的看了上面的代码肯定会发现,这样的设计跟BRIDGE模式如出一辙。其实,上面的方法也算是一种BRIDGE模式,由托管C++充当了C#
中使用用C++开发的类的桥梁。另外,这种形式也可以理解为ADAPTER模式,托管C++类Person就是C++类CPerson的一个适配器。通过
这个桥梁,可以很容易的重用以前用C++开发的类,让这些C++类继续在C#中发挥它们的效用,让开发变得事半功倍。

博客来源:http://blog.csdn.net/starlee/article/details/2864588

时间: 2024-08-29 02:46:24

在C#中使用C++编写的类——用托管C++进行封装[转]的相关文章

在C++中使用C#编写的类2

在那篇<在C#中使用C++编写的类>中我介绍了如何在C#中使用C++编写的类.可是由于C#在用户界面设计.数据库存储和XML文件读取等方面的优势,有时候也会出现要在C++中使用C#编写的类的情况.下面就用一个完整的实例来说明怎样在C++中使用C#编写的类.    比如说,现在有一个用C#编写的DLL工程CsharpDll里面有一个Person类: // Person.cs using System; namespace CsharpDll { public class Person { pub

在C#中使用C++编写的类

现在在Windows下的应用程序开发,VS.Net占据了绝大多数的份额.因此很多以前搞VC++开发的人都转向用更强大的VS.Net.在这种情况下,有很多开发人员就面临了如何在C#中使用C++开发好的类的问题.下面就用一个完整的实例来详细说明怎样用托管C++封装一个C++类以提供给C#使用. 比如,现在有一个工程名为NativeCppDll的由C++编写的DLL,里面输出了一个CPerson类.下面是具体的代码: // NativeCppDll.h #pragma once #ifndef LX_

在C#中使用C++编写的类1

转载地址:http://blog.csdn.net/starlee/article/details/2864588 现在在Windows下的应用程序开发,VS.Net占据了绝大多数的份额.因此很多以前搞VC++开发的人都转向用更强大的VS.Net.在这种情况下,有很多开发人员就面临了如何在C#中使用C++开发好的类的问题.下面就用一个完整的实例来详细说明怎样用托管C++封装一个C++类以提供给C#使用.    比如,现在有一个工程名为NativeCppDll的由C++编写的DLL,里面输出了一个

Hibernate系列(二):简单编写HibernateUtil类来优化性能

相对于Hibernate系列(一)中的代码编写HibernateUtil类以提高程序的运行速度 首先,仍然要写一个javabean(User.java): package cn.itcast.hibernate.domain; import java.util.Date; public class User { private int id; private String name; private Date birthday; public int getId() { return id; }

编写高质量代码改善C#程序的157个建议——建议112:将现实世界中的对象抽象为类,将可复用对象圈起来就是命名空间

建议112:将现实世界中的对象抽象为类,将可复用对象圈起来就是命名空间 在我们身边的世界中,对象是什么?对象就是事物,俗称“东西”.那么,什么东西算得上是一个对象呢?对象有属性.有行为.以动物为例,比如猫(Cat).Cat可以有Name,这就是属性:Cat有一个恶习ScratchSofa(挠沙发),这就是行为.我们把这些属性和行为结合起来,就称为一个类型: class Cat { public string Name { get; set; } public void ScratchSofa()

ios 中Category类别(扩展类)专题总结

原创地址   http://www.code4blog.com/archives/294 类别 类别是一种为现有的类添加新方法的方式. 利用Objective-C的动态运行时分配机制,可以为现有的类添加新方法,这种为现有的类添加新方法的方式称为类别catagory,他可以为任何类添加新的方法,包括那些没有源代码的类. 类别使得无需创建对象类的子类就能完成同样的工作 一.创建类别 1.声明类别 声明类别与声明类的形式很相似 @interface  NSString(NumberConvenienc

学习MVC之租房网站(三)-编写实体类并创建数据库

在上一篇<学习MVC之租房网站(二)-框架搭建及准备工作>中,搭建好了项目框架,并配置了EF.Log4Net和进程外Session.接下来会编写Eneity类并采用CodeFirst的方式创建数据库. 一.数据库表结构举例 1. 在按照CodeFirst方式编写Entity类之前,仍然是需要先搞清楚数据库的表结构.首先肯定会有用户.管理员.角色.权限等相关的表,然后针对租房的特殊场景,还有房屋.房屋家电配置.房子所在的地址包括城市和区域等. 2. 这里面有两张表比较特殊,T_Settings和

c语言中字符串操作的工具类

 1.编写头文件 #define _CRT_SECURE_NO_WARNINGS //#pragmawarning(disable:4996) #include <stdio.h> #include <stdlib.h> #include <string.h> struct CString { char *p;        //保存字符串首地址 int reallength; //实际长度 }; typedef struct CString mystring;//

35.按要求编写Java程序: (1)编写一个接口:InterfaceA,只含有一个方法int method(int n); (2)编写一个类:ClassA来实现接口InterfaceA,实现int method(int n)接口方 法时,要求计算1到n的和; (3)编写另一个类:ClassB来实现接口InterfaceA,实现int method(int n)接口 方法时,要求计算n的阶乘(n

  35.按要求编写Java程序: (1)编写一个接口:InterfaceA,只含有一个方法int method(int n): (2)编写一个类:ClassA来实现接口InterfaceA,实现int method(int n)接口方 法时,要求计算1到n的和: (3)编写另一个类:ClassB来实现接口InterfaceA,实现int method(int n)接口 方法时,要求计算n的阶乘(n!): (4)编写测试类E,在测试类E的main方法中使用接口回调的形式来测试实现 接口的类. p