C++/CLI 封裝總結 (也許叫備忘更好)

來源:互聯網
上載者:User

      最近在搞一個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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.