我有一个 DLL 文件,它有一个名为 trial 的类,它包含一个名为 test 的函数,我有另一个项目,我在其中使用 windows 模块的 loadlibrary 函数加载了 DLL,现在我想知道如何创建一个新项目中的型式试验对象。
我尝试将类定义为“class __declspec(dllexport) trial”,但我现在不知道如何在主文件中创建对象。
Trail.h如下:
class __declspec(dllexport) TRIALSHARED_EXPORT Trial
{
public:
Trial();
void test();
};
Trail.cpp如下:
extern "C"{
Trial::Trial(){
cout<<"object is created"<<endl;
}
void Trial:: test(){
cout<<"dynamic thingy"<<endl;
}
}
主要功能如下:
int main()
{
HINSTANCE here=LoadLibrary(L"C:\\Users\\vinay\\Documents\\qt c++\\build-trial-Desktop_Qt_5_12_0_MinGW_64_bit-Debug\\debug\\trial.dll");
if(!here){
cout<<"could not load the lib"<<std::endl;
}
else{
cout<<"library loaded"<<endl;
typedef void(*FNPTR)();
FNPTR fn=FNPTR(GetProcAddress(here,"Trial"));
fn();
}
}
最佳答案
如果您不能使用加载时绑定(bind),您应该使用带有工厂的模式。工厂创建一个实现接口(interface)的对象实例。该接口(interface)是一个抽象类,可以在消费者中使用。
像这样更改头文件:
class ITrial
{
public:
virtual void test() = 0;
};
class Trial : ITrial
{
public:
Trial();
virtual void test() override;
};
// declare a function name that can be easily found with GetProcAdress.
extern "C" TRIALSHARED_API ITrial* CreateTrial();
typedef ITrial* (*PFN_Factory)();
编辑 ITrial
类是功能的接口(interface)。您在 DLL 的实现和使用者之间定义契约。只能访问此处定义的成员。 DLL定义了一个继承自接口(interface)类的类作为实现类。实现类可以根据需要拥有任何其他成员。
编辑结束。
头文件不得包含 __declspec(dllexport)
。应使用条件编译定义宏 TRIALSHARED_EXPORT
。
#ifdef TRIAL_EXPORTS // defined only in the exporting DLL project
#define TRIALSHARED_API __declspec(dllexport)
#else
#define TRIALSHARED_API __declspec(dllimport)
#endif
添加到您的试用版:
ITrial* CreateTrial()
{
return new Trial;
}
改变你的主要功能:
int main()
{
auto here=LoadLibrary(L"C:\\Users\\vinay\\Documents\\qt c++\\build-trial-Desktop_Qt_5_12_0_MinGW_64_bit-Debug\\debug\\trial.dll");
if(!here) {
cout<<"could not load the lib"<<std::endl;
return 1;
}
auto factory = reinterpret_cast<PFN_Factory>(GetProcAddress(here, "CreateTrial"));
if (!factory) {
cout<<"could not find factory"<<std::endl;
return 1;
}
auto pTrial = factory();
if (!pTrial) {
cout<<"factory failed"<<std::endl;
return 1;
}
pTrial->test();
delete pTrial;
}
错误处理有点笨拙。根据需要更改它。
关于c++ - 如何在运行时从 C++ 中的 DLL 文件创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57805122/