C++/CLI 託管C++之類、屬性封裝【7】
阿新 • • 發佈:2019-01-08
CLI封裝類時,涉及確定性析構與非確定性析構,屬性封裝使用property。
【1】C++匯出類
class EXPORTDLL_CLASS CAddSub { public: CAddSub(){ m_len = 0; } ~CAddSub(){ } public: int Add(int x, int y){ return x+y; } int Sub(int x, int y){ return x-y; } int GetLength() { return(m_len); } void SetLength(int len){ m_len = len; } private: int m_len; };
【2】CLI類封裝
/// <summary> /// 4 類測試 /// </summary> public ref class AddSubCls { public: AddSubCls() { m_pCls = new CAddSub(); } !AddSubCls() //確定性釋放 { delete m_pCls; } ~AddSubCls() //非確定性釋放 { this->!AddSubCls(); } public: Int32 Add(Int32 x, Int32 y) { return(m_pCls->Add(x, y)); } Int32 Sub(Int32 x, Int32 y) { return(m_pCls->Sub(x, y)); } property Int32 Length { Int32 get() { return(m_pCls->GetLength()); } void set(Int32 len) { m_pCls->SetLength(len); } } private: CAddSub *m_pCls; };
C#測試函式:
AddSubCls addSubCls = new AddSubCls();
int sum = addSubCls.Add(1, 4);
addSubCls.Length = 6;