gpt4 book ai didi

C# 使用导出抽象类/接口(interface)的 C++ DLL 函数?

转载 作者:太空宇宙 更新时间:2023-11-04 14:17:54 26 4
gpt4 key购买 nike

我有一个只有一个导出函数的 DLL:

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

IRouter的接口(interface)如下:

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;
};

我有一个具体类,其接口(interface)如下:

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 使用类,但与您当前的问题表述不完全一致。

关于C# 使用导出抽象类/接口(interface)的 C++ DLL 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9775469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com