我終於想出了一個解決方案,經過幾個小時的麻煩,現在正在工作。
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