最近在搞一個C++項目的封裝工作,原項目是個native c++的項目(還是個從linux下移過來的),封裝的目地是打算
在.net下(或者說是在C#中)使用這些C++的類和它們的方法。 封裝工作的第一步,先找出原C++項目中的public class和public method. 其實它們大多被定義.h檔案中,所以把標頭檔
拷貝過來是個不錯的辦法。然後在class前上ref 把它變成managed class. 模板如下:
代碼
#include "..\cppclass.h"
#pragma once
using namespace System;
using namespace System::Text;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Data;
using namespace System::Runtime::InteropServices;
namespace CppCLI
{
public ref class CppClass
{
private:
::CppClass * _native;
public:
CppClass(::CppClass * native)
{
_native= native;
}
::CppClass* native()
{
return _native;
}
CppClass ()
{
_native = new ::CppClass();
}
~CppClass ()
{
delete _native;
}
int ok ()
{
return _native -> ok();
}
};
}
*注意:如原class沒有命名空間, 使用::表示global.
模板有了,很多簡單的方法(參數和傳回值類型簡單,如int add(int a, int b); )就可以封裝了。
在封裝的過程中,很快就會發現其實很多方法不是那麼簡單,如:
int add(int *a, int n);
void add(int a, int b, int &c);
int add(ClassA* a, ClassB* b);
ClassC* add(ClassA* a, ClassB* b);
int add(ClassA* a, ClassB* b, ClassC &c);
void print(const char* s);
int report(ostream &os);
是不是看著有點眼花?不要緊!讓我們一個一個來搞定它!(未完待續)
完整解決方案下載:CppCLI.zip