在C#中使用C++编写的类
转自 http://blog.csdn.net/starlee/article/details/2864588
现在在Windows下的应用程序开发,VS.Net占据了绝大多数的份额。因此很多以前搞VC++开发的人都转向用更强大的VS.Net。在这种情况下,有很多开发人员就面临了如何在C#中使用C++开发好的类的问题。下面就用一个完整的实例来详细说明怎样用托管C++封装一个C++类以提供给C#使用。
比如,现在有一个工程名为NativeCppDll的由C++编写的DLL,里面输出了一个CPerson类。下面是具体的代码:
- // NativeCppDll.h
- #pragma once
- #ifndef LX_DLL_CLASS_EXPORTS
- #define LX_DLL_CLASS __declspec(dllexport)
- #else
- #define LX_DLL_CLASS __declspec(dllimport)
- #endif
- class LX_DLL_CLASS CPerson
- {
- public:
- CPerson();
- CPerson(const wchar_t *pName, const wchar_t cSex, int iAge);
- void SetName(const wchar_t *pName);
- wchar_t * GetName();
- void SetSex(const wchar_t cSex);
- wchar_t GetSex();
- void SetAge(int iAge);
- int GetAge();
- wchar_t * GetLastError();
- private:
- wchar_t m_szName[128];
- wchar_t m_cSex;
- int m_iAge;
- wchar_t m_szLastError[128];
- void ShowError();
- };
- // NativeCppDll.cpp
- #include "stdafx.h"
- #include "NativeCppDll.h"
- #include <iostream>
- #include <tchar.h>
- using namespace std;
- CPerson::CPerson()
- {
- wcscpy_s(m_szName, _T("No Name"));
- m_cSex = 'N';
- m_iAge = 0;
- wcscpy_s(m_szLastError, _T("No Error"));
- }
- CPerson::CPerson(const wchar_t *pName, const wchar_t cSex, int iAge)
- {
- wcscpy_s(m_szLastError, _T("No Error"));
- SetName(pName);
- SetSex(cSex);
- SetAge(iAge);
- }
- void CPerson::SetName(const wchar_t *pName)
- {
- if ((pName == NULL) || (wcslen(pName) == 0) || (wcslen(pName) > 127))
- {
- wcscpy_s(m_szName, _T("No Name"));
- wcscpy_s(m_szLastError, _T("The length of the input name is out of range."));
- ShowError();
- return;
- }
- wcscpy_s(m_szName, pName);
- }
- wchar_t * CPerson::GetName()
- {
- return m_szName;
- }
- void CPerson::SetSex(const wchar_t cSex)
- {
- if ((cSex != 'F') && (cSex != 'M') && (cSex != 'm') && (cSex != 'f'))
- {
- m_cSex = 'N';
- wcscpy_s(m_szLastError, _T("The input sex is out of [F/M]."));
- ShowError();
- return;
- }
- m_cSex = cSex;
- }
- wchar_t CPerson::GetSex()
- {
- return m_cSex;
- }
- void CPerson::SetAge(int iAge)
- {
- if ((iAge < 0) || (iAge > 150))
- {
- m_iAge = 0;
- wcscpy_s(m_szLastError, _T("The input age is out of range."));
- ShowError();
- return;
- }
- m_iAge = iAge;
- }
- int CPerson::GetAge()
- {
- return m_iAge;
- }
- wchar_t * CPerson::GetLastError()
- {
- return m_szLastError;
- }
- void CPerson::ShowError()
- {
- cerr << m_szLastError << endl;
- }
这是一个很典型的由C++开发的DLL,输出一个完整的C++类。如果现在要求开发一个C#工程,需要用到这个DLL中输出的C++类CPerson,该怎么办呢?针对这个例子来说,类CPerson非常小,可以用C#重新写一个跟这个C++类一样的类。可是,如果需要的C++类很大,或者很多的时候,重写工程将非常庞大。而且这样没有对现有的代码进行重用,浪费了现有资源,开发起来费时费力。
当然,还是有方法解决这个问题的。那就是用托管C++将C++类给封装一下,然后再提供给C#来使用。下面就用代码来详细说明怎样用托管C++来封装上面的那个C++类。
首先,要创建一个托管C++的DLL工程ManageCppDll,然后在里面添加下面的代码:
- // ManageCppDll.h
- #pragma once
- #define LX_DLL_CLASS_EXPORTS
- #include "../NativeCppDll/NativeCppDll.h"
- using namespace System;
- namespace ManageCppDll
- {
- public ref class Person
- {
- // 包装所有类CPerson的公有成员函数
- public:
- Person();
- Person(String ^ strName, Char cSex, int iAge);
- ~Person();
- property String ^ Name
- {
- void set(String ^ strName);
- String ^ get();
- }
- property Char Sex
- {
- void set(Char cSex);
- Char get();
- }
- property int Age
- {
- void set(int iAge);
- int get();
- }
- String ^ GetLastError();
- private:
- // 类CPerson的指针,用来调用类CPerson的成员函数
- CPerson *m_pImp;
- };
- };
从这个头文件就能看出来,这是对C++类CPerson的包装。类Person的所有公有成员函数都跟C++类CPerson一样,只不过成员函数的参数和返回值就改成了托管C++的类型,这也是让类Person能在C#中使用的首要条件。当然只需要对公有成员函数进行封装,对于保护成员函数和私有成员函数则不必做任何封装。
类Person仅有一个私有的成员变量:一个类CPerson的指针。而类Person的所有成员函数的实现都是靠这个CPerson指针来调用类CPerson的相应成员函数来实现。
下面是具体的实现代码:
- // ManageCppDll.cpp
- #include "stdafx.h"
- #include "ManageCppDll.h"
- #include <vcclr.h>
- namespace ManageCppDll
- {
- // 在构造函数中创建类CPerson的对象并在析构函数中将该对象销毁
- // 所有的成员函数实现都是通过指针m_pImp调用类CPerson的相应成员函数实现
- Person::Person()
- {
- m_pImp = new CPerson();
- }
- Person::Person(String ^ strName, Char cSex, int iAge)
- {
- // 将string转换成C++能识别的指针
- pin_ptr<const wchar_t> wcName = PtrToStringChars(strName);
- m_pImp = new CPerson(wcName, cSex, iAge);
- }
- Person::~Person()
- {
- // 在析构函数中删除CPerson对象
- delete m_pImp;
- }
- void Person::Name::set(String ^ strName)
- {
- pin_ptr<const wchar_t> wcName = PtrToStringChars(strName);
- m_pImp->SetName(wcName);
- }
- String ^ Person::Name::get()
- {
- return gcnew String(m_pImp->GetName());
- }
- void Person::Sex::set(Char cSex)
- {
- m_pImp->SetSex(cSex);
- }
- Char Person::Sex::get()
- {
- return m_pImp->GetSex();
- }
- void Person::Age::set(int iAge)
- {
- m_pImp->SetAge(iAge);
- }
- int Person::Age::get()
- {
- return m_pImp->GetAge();
- }
- String ^ Person::GetLastError()
- {
- return gcnew String(m_pImp->GetLastError());
- }
- };
如果要在C#中使用类Person,首先要添加对ManageCppDll.dll的引用,然后就可以像用普通的C#类一样的使用类Person了。比如下面这样的代码:
- using ManageCppDll;
- Person person = new Person();
- person.Name = "StarLee";
- person.Sex = 'M';
- person.Age = 28;
熟悉设计模式的看了上面的代码肯定会发现,这样的设计跟BRIDGE模式如出一辙。其实,上面的方法也算是一种BRIDGE模式,由托管C++充当了C#中使用用C++开发的类的桥梁。另外,这种形式也可以理解为ADAPTER模式,托管C++类Person就是C++类CPerson的一个适配器。通过这个桥梁,可以很容易的重用以前用C++开发的类,让这些C++类继续在C#中发挥它们的效用,让开发变得事半功倍。
================================================================================
在C++中使用C#编写的类
转自 http://blog.csdn.net/starlee/article/details/2897970
在那篇《在C#中使用C++编写的类》中我介绍了如何在C#中使用C++编写的类。可是由于C#在用户界面设计、数据库存储和XML文件读取等方面的优势,有时候也会出现要在C++中使用C#编写的类的情况。下面就用一个完整的实例来说明怎样在C++中使用C#编写的类。
比如说,现在有一个用C#编写的DLL工程CsharpDll里面有一个Person类:
- // Person.cs
- using System;
- namespace CsharpDll
- {
- public class Person
- {
- public Person()
- {
- Name = "No Name";
- Sex = 'N';
- Age = 0;
- m_strLastError = "No Error";
- }
- public Person(string strName, char cSex, int iAge)
- {
- m_strLastError = "No Error";
- Name = strName;
- Sex = cSex;
- Age = iAge;
- }
- public string Name
- {
- get
- {
- return m_strName;
- }
- set
- {
- if ((String.IsNullOrEmpty(value)) || (value.Length > 127))
- {
- m_strName = "No Name";
- m_strLastError = "The length of the input name is out of range.";
- return;
- }
- m_strName = value;
- }
- }
- public char Sex
- {
- get
- {
- return m_cSex;
- }
- set
- {
- if ((value != 'F') && (value != 'M') && (value != 'm') && (value != 'f'))
- {
- m_cSex = 'N';
- m_strLastError = "The input sex is out of [F/M].";
- return;
- }
- m_cSex = value;
- }
- }
- public int Age
- {
- get
- {
- return m_iAge;
- }
- set
- {
- if ((value < 0) || (value > 150))
- {
- m_iAge = 0;
- m_strLastError = "The input age is out of range.";
- return;
- }
- m_iAge = value;
- }
- }
- public string LastError
- {
- get
- {
- return m_strLastError;
- }
- }
- private string m_strName;
- private char m_cSex;
- private int m_iAge;
- private string m_strLastError;
- }
- }
如果需要在C++中使用这个C#编写的Person类,就需要用托管C++来对这个C#进行包装,将它包装成一个C++能用的类。
首先,要创建一个托管C++的DLL工程ManageCppDll。并且,要添加对CsharpDll.dll的引用。然后对C#类所有的公有属性和方法进行包装。下面是具体的代码:
- // ManageCppDll.h
- #pragma once
- #ifndef LX_DLL_CLASS_EXPORTS
- #define LX_DLL_CLASS __declspec(dllexport)
- #else
- #define LX_DLL_CLASS __declspec(dllimport)
- #endif
- class LX_DLL_CLASS CPerson
- {
- public:
- CPerson();
- CPerson(const wchar_t *pName, const wchar_t cSex, int iAge);
- ~CPerson();
- void SetName(const wchar_t *pName);
- wchar_t * GetName();
- void SetSex(const wchar_t cSex);
- wchar_t GetSex();
- void SetAge(int iAge);
- int GetAge();
- wchar_t * GetLastError();
- private:
- // 用一个void指针指向Person的对象
- // 所有公有成员函数的实现都是通过这个对象来实现
- void *m_pImp;
- wchar_t m_szName[128];
- wchar_t m_szLastError[128];
- };
- // ManageCppDll.cpp
- #include "stdafx.h"
- #include "ManageCppDll.h"
- #include <vcclr.h>
- #include <string.h>
- #include <stdlib.h>
- using namespace System;
- using namespace System::Runtime::InteropServices;
- using namespace CsharpDll;
- // 将GCHandle转换成为void指针
- #define __GCHANDLE_TO_VOIDPTR(x) ((GCHandle::operator System::IntPtr(x)).ToPointer())
- // 将void指针转换为GCHandle
- #define __VOIDPTR_TO_GCHANDLE(x) (GCHandle::operator GCHandle(System::IntPtr(x)))
- // 辅助函数
- // 将void指针指向的对象转换成为Person对象
- inline Person ^ GetImpObj(void *pHandle)
- {
- Person ^ person = nullptr;
- if (pHandle != NULL)
- {
- person = static_cast<Person^>(__VOIDPTR_TO_GCHANDLE(pHandle).Target);
- }
- return person;
- }
- CPerson::CPerson()
- {
- m_pImp = NULL;
- Person ^ person = gcnew Person();
- // 创建GCHandle并将它转换成void指针保存到成员变量中
- GCHandle handle = GCHandle::Alloc(person);
- m_pImp = __GCHANDLE_TO_VOIDPTR(handle);
- }
- CPerson::CPerson(const wchar_t *pName, const wchar_t cSex, int iAge)
- {
- m_pImp = NULL;
- Person ^ person = gcnew Person();
- person->Name = gcnew String(pName);
- person->Sex = cSex;
- person->Age = iAge;
- GCHandle handle = GCHandle::Alloc(person);
- m_pImp = __GCHANDLE_TO_VOIDPTR(handle);
- }
- CPerson::~CPerson()
- {
- if (m_pImp == NULL)
- return;
- // 释放GCHandle
- GCHandle handle = __VOIDPTR_TO_GCHANDLE(m_pImp);
- handle.Free();
- m_pImp = NULL;
- }
- void CPerson::SetName(const wchar_t *pName)
- {
- // 将void指针转换成Person指针
- // 并用该指针调用相应的公有属性或方法
- Person ^ person = GetImpObj(m_pImp);
- person->Name = gcnew String(pName);
- }
- wchar_t * CPerson::GetName()
- {
- Person ^ person = GetImpObj(m_pImp);
- // 将C#返回的字符串转换为wchat_t*指针能指向的地址
- wchar_t * pName = static_cast<wchar_t*>(Marshal::StringToHGlobalUni(person->Name).ToPointer());
- wcscpy_s(m_szName, pName);
- Marshal::FreeHGlobal(System::IntPtr(pName)); // 释放内存
- return m_szName;
- }
- void CPerson::SetSex(const wchar_t cSex)
- {
- Person ^ person = GetImpObj(m_pImp);
- person->Sex = cSex;
- }
- wchar_t CPerson::GetSex()
- {
- Person ^ person = GetImpObj(m_pImp);
- return person->Sex;
- }
- void CPerson::SetAge(int iAge)
- {
- Person ^ person = GetImpObj(m_pImp);
- person->Age = iAge;
- }
- int CPerson::GetAge()
- {
- Person ^ person = GetImpObj(m_pImp);
- return person->Age;
- }
- wchar_t * CPerson::GetLastError()
- {
- Person ^ person = GetImpObj(m_pImp);
- wchar_t * pLastError = static_cast<wchar_t*>(Marshal::StringToHGlobalUni(person->LastError).ToPointer());
- wcscpy_s(m_szLastError, pLastError);
- Marshal::FreeHGlobal(System::IntPtr(pLastError));
- return m_szLastError;
- }
现在对上面代码中所用到的一些相关背景知识进行一下介绍。
GCHandle结构提供从非托管内存访问托管对象的方法。
GCHandle.Alloc方法(Object)为指定的对象分配Normal句柄。它保护对象不被垃圾回收。当不再需要GCHandle时,必须通过Free将其释放。Normal句柄类型表示不透明句柄,这意味着无法通过此句柄解析固定对象的地址。可以使用此类型跟踪对象,并防止它被垃圾回收器回收。当非托管客户端持有对托管对象的唯一引用(从垃圾回收器检测不到该引用)时,此枚举成员很有用。
上面的代码中,在类CPerson的构造函数中用GCHandle为C#类Person的对象分配一个句柄,并将该句柄转换为void指针存放在成员变量中,以保证这个对象不会被垃圾回收器回收。然后在类CPerson的析构函数中释放这个句柄,将C#类Person的对象的回收权交给系统。
Marshal类提供了一个方法集,这些方法用于分配非托管内存、复制非托管内存块、将托管类型转换为非托管类型,此外还提供了在与非托管代码交互时使用的其他杂项方法。
Marshal..::.StringToHGlobalUni方法向非托管内存复制托管String的内容。StringToHGlobalUni对于自定义封送处理或者在混合托管和非托管代码时很有用。由于该方法分配字符串所需的非托管内存,因此应始终通过调用FreeHGlobal释放内存。
(更多关于上面介绍的背景知识可以搜索MSDN。说实在的MSDN真是一个宝库!VS能在Windows平台开发中取得绝大多数的份额,除了因为它和Windows都是微软开发的之外,MSDN的完备性功不可没!)
通过上面的方法,就把一个C#编写的类Person用托管C++给封装成了一个C++可以使用的CPerson类。我们可以在C++的工程中像使用一般的C++类一样使用类CPerson。比如下面的代码。
- CPerson person(_T("StarLee"), 'M', 28);
- person.SetName(_T("StarLee"));
- person.SetSex('M');
- person.SetAge(28);
- wcout << "Name: " << person.GetName() << " Sex: " << person.GetSex() << " Age: " << person.GetAge() << endl;
- wcout << "Error: " << person.GetLastError() << endl;
这里的方法跟《在C#中使用C++编写的类》一样,都是借用托管C++这个桥梁来沟通C++编写的类和C#编写的类,使在C++中使用C#编写的类和在C#中使用C++编写的类成为现实。