gpt4 book ai didi

c++ - 多态 DLL 导出

转载 作者:太空宇宙 更新时间:2023-11-04 13:55:37 28 4
gpt4 key购买 nike

我目前正在开发一个使用 DLL 的项目和一个使用 DLL 的应用程序。像往常一样,DLL 作为抽象基类头和从抽象基派生的具体实现导出:

---- TaskInterface.h ----
class Task {
public:
virtual int func1(void) = 0;
virtual int func2(void) = 0;
};

extern "C" __declspec(dllexport) Task * APIENTRY newTask();

--- Task.h ---
class TaskImpl : public Task
{
public:
virtual int func1(void);
virtual int func2(void):
};

Task * APIENTRY newTask()
{
return static_cast<Task*>( new TaskImpl );
}

--- Task.cpp ---
int TaskImpl::func1(void)
{
// ...
}

int TaskImpl::func2(void)
{
// ...
}

这按预期工作,应用程序包含“AbstractTask.h”,然后调用由类 TaskImpl 定义的相应函数:

--- TheApplication.cpp ---
Task aTask = newTask();
aTask->func1();
aTask->func2();
// ...

但是,现在应用程序发现类 TaskImpl 中的默认实现所做的还不够,因此在其自己的范围内定义了一个新的派生类,如下所示:

--- AppImpl.h ---
#include "TaskInterface.h"

class AppImpl : public Task
{
int func1(void) = { /* new stuff */ }
int func2(void) = { /* new stuff */ }
};

然后在TheApplication.cpp中定义:

--- TheApplication.cpp ---

#include "AppImpl.h"
ApplImp * aNewTask = static_cast<Task*>(newTask());

aNewTask->func1();
aNewTask->func2();

您认为 func1() 和 func2() 在什么情况下被调用?正确:它仍然是 DLL 类 TaskImpl 内部的具体实现,而不是类 AppImpl 定义的派生类。

基本上这是我的问题:我想使用 DLL 内部的默认实现,但我希望能够在应用程序端扩展它,所以除非我在 ApplImp.h 中明确覆盖了一个函数,否则我回退到 DLL 内的 TaskImpl 中定义的那个。

这可能吗?如果是这样,我做错了什么?如果不是,我怎么能完成同等的事情?

我已经尝试过同时导出“TaskInterface.h”和“Task.h”,然后让 ApplImp.h 在 DLL 中包含具体类,但由于显而易见的原因编译不喜欢那样 => 不能导出 newTask() 两次。

感谢任何帮助!

最佳答案

由于您无论如何都需要通过 DLL 分配和解除分配,因此我建议在 DLL 旁边提供一个包装器类。然后可以将此包装类设计为从中继承。

class Task {
public:
virtual int func1(void) = 0;
virtual int func2(void) = 0;
};

// v~~~~v probably dllimport in the header you ship
extern "C" __declspec(dllexport) Task * APIENTRY newTask();

class TaskWrapper {
public:
TaskWrapper() : m_ptr( newTask() ) {}
virtual ~TaskWrapper() { deleteTask(m_ptr); }

virtual int func1(void) { m_ptr->func1(); }
virtual int func2(void) { m_ptr->func2(); }

protected: // implementation omitted for brevity
TaskWrapper(TaskWrapper const&);
TaskWrapper(TaskWrapper&&);

TaskWrapper& operator= (TaskWrapper const&);
TaskWrapper& operator= (TaskWrapper&&);

private:
Task* m_ptr; // preferably a unique_ptr
};

您还可以让 TaskWrapperTask 派生。

关于c++ - 多态 DLL 导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632195/

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