2012-05-16 42 views
3

我的第三方dll中有一個C++類。如何在c#代碼中訪問C++ dll類

如果我調用Assembly.LoadFrom(),VS拋出一個未處理的異常,因爲模塊中沒有包含任何清單。

我可以使用DllImport調用全局函數來獲取某個類的實例。

我該如何調用其成員函數之一?

+2

看看 「從C#調用C++未管理的類的」 http://博客。 msdn.com/b/sanpil/archive/2004/07/07/175855.aspx – volody

回答

2

創建C++/CLI將C++函數

例如包裝DLL:

//class in the 3rd party dll 
class NativeClass 
{ 
    public: 
    int NativeMethod(int a) 
    { 
     return 1; 
    } 
}; 

//wrapper for the NativeClass 
class ref RefClass 
{ 
    NativeClass * m_pNative; 

    public: 
    RefClass():m_pNative(NULL) 
    { 
     m_pNative = new NativeClass(); 
    } 

    int WrapperForNativeMethod(int a) 
    { 
     return m_pNative->NativeMethod(a); 
    } 

    ~RefClass() 
    { 
     this->!RefClass(); 
    } 

    //Finalizer 
    !RefClass() 
    { 
     delete m_pNative; 
     m_pNative = NULL; 
    } 
};