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

C# consumption of C++ DLL function that exports an abstract class/interface?

本文关键字:C++DLL 函数 接口 抽象类      更新时间:2023-10-16

我有一个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派生的对象?

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

使用p/Invoke或COM.

使用类也是可能的,但与您当前的问题表述不完全一致