我终于想出了一个解决方案,经过几个小时的麻烦,现在正在工作。
QLibrary类允许动态加载.dll文件,所以我所要做的就是将我的类放入.dll,并添加一个函数,该函数返回指向所需类的指针。
这是.dll's头文件:
#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's CPP文件:
#include "testfixture.h"
DivFixture::DivFixture(){}
extern "C" __declspec(dllexport) void DivFixture::setNumerator(QVariant num)
{
numerator=num.toDouble();
}
extern "C" __declspec(dllexport) void DivFixture::setDenominator(QVariant denom)
{
denominator=denom.toDouble();
}
extern "C" __declspec(dllexport) 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();
}
}
之后,我可以得到QMetaObject并调用我喜欢的任何方法。 希望这有助于那些将来会面临类似问题的人。
在C++中没有简单的方法来“动态加载类”。只有很难的方法。 – Mat
我明白了。猜猜我会用插件去。谢谢! – LarissaGodzilla
对,对不起: -/[this](http://drdobbs.com/cpp/204202899?cid=RSSfeed%255FDDJ%255FCpp)可能会有所帮助。玩的开心! – Mat