Including class files dynamically

I am currently working on porting the Fitnesse Slim server from java to Qt, which requires me to be able to load classes that do not yet exist.

I already figured out how to create an instance of an unknown class here: How can I get QMetaObject only from the class name? But for this I need the class.h file to be already included, right?

So, I was thinking of doing this with plugins. I will make one class interface and load the required class files as DLL files. It seems like a little work just to include class files. Is there an easier way to do this?

EDIT: I tried to do this using plugins now and it does not work. The problem is this:
In my interface I have to name methods, for example "setAttribute".
But my plugin must have method names, for example "setNumerator".
Therefore, I cannot map my plugin to my interface. Which leaves me wondering if there is any way to enable my plugin without having to declare the interface first. Any ideas?

+4
source share
1 answer

Finally, I came up with a solution that now works after several hours of work.

The QLibrary class allows you to load DLL files dynamically, so all I had to do was put my class in a .dll and add a function that returns a pointer to the required class.

This is the header .dll 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 cpp.dll file:

 #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(); } 

and so 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(); } } 

After that, I can get a QMetaObject and call any method that I like. Hope this helps those facing a similar problem in the future.

+1
source

All Articles