2012-03-19 48 views
1

我有隻有一個出口函數的DLL:C#使用C++ DLL函數導出抽象類/接口?

#ifdef __cplusplus 
extern "C" 
{ 
    __declspec(dllexport) IRouter* CreateRouter(); 
} 
#endif 

爲IRouter的界面如下:

class IRouter 
{ 
public: 
    virtual bool __stdcall DoSomething(LPCWSTR szCommand) = 0; 
    // Call Release() from DLL client to free any memory associated with this object 
    virtual bool __stdcall Release() = 0; 
}; 

,我有一個具體的類,它的界面如下:

class CMyRouter : public IRouter 
{ 
public: 
    bool __stdcall DoSomething(LPCWSTR szCommand); 
    bool __stdcall Release(); 
} 

正如您所料,MyRouter類的實現包含在DLL中。

爲我的單導出功能的代碼如下:

#ifdef __cplusplus 
extern "C" 
{ 
    __declspec(dllexport) IRouter* CreateRouter() 
    { 
     return new CMyRouter; 
    } 
} 
#endif // __cplusplus 

我的問題是:如何從C#客戶訪問我IRouter派生的對象?

回答

0

您可以在C++/CLI中執行此操作(使用聚合,而不是繼承)。例如,在C++/CLI中創建一個與C++抽象類IRouter相對應的託管類,並提供幾種轉發方法,如`DoSomething(string)。然後,您可以在C#中實現其餘的託管邏輯。

也可以但不完全符合您當前提出的問題,使用P/Invoke或COM來使用該類。

+0

感謝您的幫助。如果我理解正確,我需要編寫另一個C++/CLI DLL作爲我的本地C++ DLL和我的C#客戶端之間的中介。你知道這種C++/CLI聚合解決方案的例子嗎?你說得對,我打算使用P/Invoke來學習這個類。 – markiemooster 2012-03-20 10:26:28

+0

@markiemooster - 如果你使用C++/CLI,你將不需要P/Invoke。您只需在Visual Studio中創建一個C++/CLI項目並學習該語言的基礎知識(例如,[here] [1])(您還收到了Nanhydrin答覆的P/Invoke方式的答案,但它是非常不尋常和不便使用P/Invoke類方法。) – 2012-03-20 11:35:31

+0

@markiemooster - 我忘了粘貼鏈接:[http://www.codeproject.com/Articles/19354/Quick-C-CLI-Learn-C- CLI-in-less-than-10-minutes] – 2012-03-20 11:36:11