Is there any way to load a library dynamically?
Hi, I use Qt 4.7 on a Mac. I created several custom widgets. These widgets are compiled into a .dylib file installed in designer's plugin directory. When I open the designer in the Qt Creator, the .dylib is loaded. So I can use my widgets in my .ui file without any problem. Now I want to create different versions of the widgets/.dylib for different projects. And I want to load the right version of the .dylib for a specific project. Is there any way to achieve this?
If you mean loading DLLs at runtime, you need to use QLibrary.
[quote author="sierdzio" date="1376111760"]If you mean loading DLLs at runtime, you need to use QLibrary.[/quote]
AFAIK, this only works with "plain C" functions, but not with C++ objects. I never managed to load C++ objects dynamically (at runtime) from a DLL. It requires linking against the DLL via import library (.LIB file), I think.
One workaround is to export some wrapper functions from the DLL:
__declspec(dllexport) MyClass* __cdecl newObject(void)
return new MyClass();
__declspec(dllexport) int __cdecl useObject(MyClass *o)
__declspec(dllexport) void __cdecl delObject(MyClass *o)
Then use like this in the EXE file:
typedef MyClass* (*NewObjetFunc)(void);
typedef int (UseObjetFunc)(MyClass);
typedef void (DelObjetFunc)(MyClass);
NewObjectFunc newObjectPtr = NULL;
UseObjectFunc useObjectPtr = NULL;
DelObjectFunc delObjectPtr = NULL;
newObjectPtr = (NewObjectFunc) myLib.resolve("newObject");
useObjectPtr = (UseObjectFunc) myLib.resolve("useObject");
delObjectPtr = (DelObjectFunc) myLib.resolve("delObject");
if(newObjectPtr && useObjectPtr && delObjectPtr)
MyClass *obj = newObjectPtr();
int result = useObjectPtr(obj); //Actually use object here! delObjectPtr(obj); obj = NULL;
QLibrary is - as MuldeR said - for C functions resolving.
You can use QPlugInLoader for loading C++ functions, but only when they are using "Qt plugin mechanismns":http://qt-project.org/doc/qt-5.0/qtcore/plugins-howto.html. Or link to them dynamically.
Please note that for C++ symbol resolving the various things (e.g., compiler version, build mode, etc.) need to match in order to load a plugin successfully.
Thanks for all the help. I will try to see which method is proper to my case.