我正在尝试动态地包含类文件,并选择通过将.dll加载到QLibrary中来实现。我现在遇到的问题是,当我尝试调用resolve() - 方法时,它返回0。
编辑: 在此期间问题已经解决,我决定编辑代码,以便其他人可以看到它是如何工作的:
这是.dll的头文件:
#ifndef DIVFIXTURE_H
#define DIVFIXTURE_H
#include<QObject>
#include<QVariant>
class __declspec(dllexport) DivFixture : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE DivFixture();
Q_INVOKABLE void setNumerator(QVariant num);
Q_INVOKABLE void setDenominator(QVariant denom);
Q_INVOKABLE QVariant quotient();
private:
double numerator, denominator;
};
#endif
这是dll的.cpp文件:
#include "testfixture.h"
DivFixture::DivFixture(){}
void DivFixture::setNumerator(QVariant num)
{
numerator=num.toDouble();
}
void DivFixture::setDenominator(QVariant denom)
{
denominator=denom.toDouble();
}
QVariant DivFixture::quotient()
{
QVariant ret;
ret=numerator/denominator;
return ret;
}
//non-class function to return pointer to class
extern "C" __declspec(dllexport) DivFixture* create()
{
return new DivFixture();
}
这就是我加载课程的方式:
currentFixture.setFileName("C:\\somepath\\testFixture.dll");
if(currentFixture.load());
{
typedef QObject* (*getCurrentFixture)();
getCurrentFixture fixture=(getCurrentFixture)currentFixture.resolve("create");
if (fixture)
{
Fixture=fixture();
}
}
答案 0 :(得分:2)
class __declspec(dllexport) DivFixture : public QObject
{
答案 1 :(得分:0)
接受的答案是不正确的。 __declspec
有两个可能的参数:
在编译库时使用dllexport,在链接时使用dllimport。
Qt已经为此提供了定义:
要正确使用它们,请添加以下内容:
#if defined(MYSHAREDLIB_LIBRARY)
# define MYSHAREDLIB_EXPORT Q_DECL_EXPORT
#else
# define MYSHAREDLIB_EXPORT Q_DECL_IMPORT
#endif
到项目中的全局标题,您将包含在要导出的所有类中。然后修改你的类,最后声明如下:
class MYSHAREDLIB_EXPORT DivFixture : public QObject
Qt的文档Creating Shared Libraries中提供了完整的示例和更多信息。