2013-03-19 53 views

回答

1

是的。這裏有一些指南。混合CLI/C++和本地代碼。你不需要一個包裝器來在CLI/C++中使用它們。實際上,您使用CLI/C++和本機代碼來創建包裝。

http://www.technical-recipes.com/2012/mixing-managed-and-native-types-in-c-cli/

http://www.codeproject.com/Articles/35041/Mixing-NET-and-native-code

如果你實際上是試圖使包裝在C#中使用,它應該是這個樣子:

#include "NativeClass.h" 

public ref class NativeClassWrapper { 
    NativeClass* m_nativeClass; 

public: 
    NativeClassWrapper() { m_nativeClass = new NativeClass(); } 
    ~NativeClassWrapper() { delete m_nativeClass; } 
    void Method() { 
     m_nativeClass->Method(); 
    } 

protected: 
    // an explicit Finalize() method—as a failsafe 
    !NativeClassWrapper() { delete m_nativeClass; } 
}; 

參考C++/CLI wrapper for native C++ to use as reference in C#

+1

是的,這實際上是你如何製作包裝。 :] – Corylulu 2013-03-19 17:11:36

+0

這是如何創建一個包裝器,但如果您在C++中使用它,則不需要。如果你想把它帶到C#,那麼是的,這是你需要的。我注意到你標記了C#,所以也許這就是你想要做的。 – Corylulu 2013-03-19 17:14:45

+0

更好的主意:使用一個工作智能指針,如[我寫的這一個](http://codereview.stackexchange.com/q/1695/2150),而不是複製每個包裝類中的內存清理代碼。例如,這個答案有內存泄漏。 – 2013-03-19 17:19:17

1

使用智能指針庫使管理本地(而不是垃圾回收)對象的分配變得更加簡單CTS,這是相當困難的例外,多次調用Dispose()的存在,忘記打電話Dispose()

這裏的Dr_Asik的例子,改寫使用a smart pointer I wrote

#include "clr_scoped_ptr.h" 
#include "NativeClass.h" 

public ref class NativeClassWrapper { 
    clr_scoped_ptr<NativeClass> m_nativeClass; 

public: 
    NativeClassWrapper() m_nativeClass(new NativeClass()) {} 
    // auto-generated destructor is correct 
    // auto-generated finalizer is correct 

    void Method() { 
     m_nativeClass->Method(); 
    } 
}; 

進行字符串轉換,使用marshal_as Microsoft爲此目的提供的類。檢查出ildjarn的答案在這裏:C++/CLI String Conversions

+0

感謝您的明智回答,本,我接受它,直到有人提出更好的答案。你似乎是一個C++專家,由你的SO代表來評判這件事(金C++徽章,有多少人擁有這些徽章?!),所以我相信你確切地知道你在這裏談論的是什麼。與我自己一樣,一個初學者。呃..有一天! – 2013-03-19 17:34:21

+0

@Geotarget:SO代表和徽章不是最可靠的指標,但我喜歡認爲我給出了很好的答案。繼續練習,你也會發展專業知識。 – 2013-03-19 17:35:23

+0

你能告訴我一些關於將C#數據類型轉換爲C++並返回的信息嗎?只是基本的字符串和整數/雙打。我在這裏獲得了一些字符串參考代碼:http://www.codeproject.com/Articles/35041/Mixing-NET-and-native-code但是一切仍然非常片斷。 – 2013-03-19 17:35:28

相關問題