导出抽象类/接口的C ++ DLL函数的C#消耗?

时间:2012-03-19 18:07:31

标签: c# c++ dll interface

我有一个只有一个导出函数的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派生对象?

2 个答案:

答案 0 :(得分:0)

查看这篇文章Inheriting From a Native C++ Class in C#,它可能会有帮助。

答案 1 :(得分:0)

您可以在C ++ / CLI中执行此操作(使用聚合,而不是继承)。例如,在C ++ / CLI中创建一个托管类,该托管类对应并保存指向C ++抽象类IRouter的指针,并提供一些转发方法,如`DoSomething(string)。然后,您可以在C#中实现其余的托管逻辑。

使用P / Invoke或COM使用类也可能(但不完全符合当前问题的表述)。