I´m trying to inc开发者_Go百科lude classfiles dynamically right now and chose to do so by loading the .dll into a QLibrary. The problem I´m having now is, that when I try to call the resolve()-method it returns 0.
EDIT: In the meantime the problem has been solved and I decided to edit the code, so others can see how it works:
This is the .dll´s header file:
#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
this is the dll´s .cpp-file:
#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();
}
And this is how I load my class:
currentFixture.setFileName("C:\\somepath\\testFixture.dll");
if(currentFixture.load());
{
typedef QObject* (*getCurrentFixture)();
getCurrentFixture fixture=(getCurrentFixture)currentFixture.resolve("create");
if (fixture)
{
Fixture=fixture();
}
}
You need to export your class using __declspec(dllexport)
class __declspec(dllexport) DivFixture : public QObject
{
The accepted answer isn't correct. __declspec
has two possible parameters:
- dllexport
- dllimport
dllexport being used when compiling the library and dllimport when linking to it.
Qt already provides defines for that:
- Q_DECL_EXPORT
- Q_DECL_IMPORT
To make proper use of them, add something like:
#if defined(MYSHAREDLIB_LIBRARY)
# define MYSHAREDLIB_EXPORT Q_DECL_EXPORT
#else
# define MYSHAREDLIB_EXPORT Q_DECL_IMPORT
#endif
to a global header in your project that you will include in all classes you want to export. Then modify your classes so in the end the declaration looks like:
class MYSHAREDLIB_EXPORT DivFixture : public QObject
A complete example and more information are given in the Creating Shared Libraries of Qt's documentation.
精彩评论