我有一个当前在 .lib 文件中的类:
class __declspec(dllexport) ReportData {
public:
list<FileData *> ReportFileData;
list<SupressionData *> ReportSupressionData;
static char *ClientName;
static char *DataRecieved;
std::string GenFileConfTemplate();
~ReportData()
{
ReportFileData.clear();
ReportSupressionData.clear();
}
};
我可以将这个 lib 文件添加到我的项目中并创建此类的实例,没问题。 我的问题是,如何将它移动到 DLL 并动态加载它,并创建此类的实例。我想要做的是将一些通用功能移到这个 dll 中并在多个项目中共享它。
我希望能够在进行更改时根据需要重新编译 dll,并让项目使用必须的最新版本;截至目前,使用 lib,我必须在重新编译 dll 后重新编译每个项目才能进行更改,并且由于该系统最初设计的方式,有 100 多个项目将使用此 lib/dll,而我不想每次进行更改时都重新编译 100 个不同的项目。
那么,请就我应该如何着手提供您的专家意见。
我将像这样在我的项目中使用 dll:
ReportData *rd = new ReportData();
ReportData::ClientName = "test";
rd->ReportFileData.push_back(new FileData("testing", 10, 1));
rd->ReportFileData.push_back(new FileData("testing 2", 20, 1));
std::cout << rd->GenFileConfTemplate();
delete rd;
我最终得到了这样的东西:
typedef Foo* (__stdcall *CreateFunc)();
int main()
{
HMODULE dll (LoadLibrary ("..\\LLFileConfirmDLL\\LLFileConfirmDLL.dll"));
if (!dll) {
cerr << "LoadLibrary: Failed!" << endl;
std::cin.get();
return 1;
}
CreateFunc create (reinterpret_cast<CreateFunc>(GetProcAddress (dll, "create")));
if (!create) {
cerr << "GetProcAddress: Failed!" << endl;
std::cin.get();
return 1;
}
Foo *f = create();
cerr << f->Test();
FreeLibrary (dll);
std::cin.get();
return 0;
}
struct FOOAPI Foo
{
Foo();
virtual ~Foo();
virtual int Test();
};
Foo::Foo()
{
}
Foo::~Foo()
{
}
int Foo::Test()
{
return 5;
}
extern "C" __declspec(dllexport) Foo* __stdcall create()
{
return new Foo;
}
最佳答案
您可以按照 COM 的方式执行此操作:
- 导出一个 CreateInstance() 函数。
- 将 void** 和唯一标识符传递给 CreateInstance()。
- 您的消费 DLL 调用库 DLL 上的 LoadLibrary() 并调用 CreateInstance()。
- CreateInstance() 执行新的 ReportData 并在 void** out 参数中返回它。
编辑:
类似于:
extern "C"
BOOL CreateObject(REFCLSID rclsid, void** ppv) {
BOOL success = false;
*ppv = NULL;
if (rclsid == CLSID_ReportData) {
ReportData* report_data = new ReportData();
if (report_data) {
*ppv = report_data;
success = true;
}
} else if (...) {
... other objects ...
}
return success;
}
当然,现在您必须担心诸如谁将释放对象、确保 DLL 不会被卸载等问题。
关于c++ - 显式链接到 DLL 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1027435/