Question

Is delayed DLL loading possible in QT? For example, my program has dependency from some third-party DLL and I want to remove it.

What should I write in .pro file to remove dependency?

Can I store DLL in resources?

Can I load DLL "globally"? So some function from DLL (for example func1) will remain func1 in my code.

Was it helpful?

Solution

Yes, you want to use the QLibrary class. It is specifically provided to load shared libraries at runtime.

In this case you do not need anything in your .pro file. However, you need to make sure the DLL is available on the target computers. It either needs to be in a location where the system can find it (PATH on Windows, LD_LIBRARY_PATH on Linux, DYLD_LIBRARY_PATH on Mac) or you can provide an absolute path from your application.

If you look at the documentation you will see how to map a library function to a function pointer in your code so that "func1()" will point to the function in your library.

[EDIT]

Here is a proof-of-concept to load a dll from a temp file generated from a resource. IMO, this is a Really Bad Idea, but it at least works on my Windows 7 machine. If you want to do something similar, you will have to handle cleaning up the temp file, checking for duplicates, etc.

foo.cpp, compiled into a shared library

#include <QtCore/qglobal.h>

extern "C" Q_DECL_EXPORT int foo(int value) {
  return value + 42;
}

bar.pro, notice no reference to foo library

SOURCES += main.cpp
RESOURCES += resources.qrc

main.cpp

#include <QtCore>
#include <iostream>

int main(int argc, char **argv) {
  QCoreApplication app(argc, argv);

  // Copy resource dll to temporary file.
  QFile::copy(":/lib/Foo.dll", QDir::temp().filePath("Foo.dll"));

  // Load the temporary file as a shared library.
  QLibrary foo_lib(QDir::temp().filePath("Foo.dll"));
  typedef int (*FooDelegate)(int);
  FooDelegate foo = (FooDelegate)foo_lib.resolve("foo");

  if (foo) {
    std::cout << "foo(13) = " << foo(13) << std::endl;
  }
}

OTHER TIPS

I can only speak from a Microsoft compiler perspective... It depends less on what QT wants than it does on when and where the delay loaded code and/or data is accessed.

In general, you have to tell the linker that the DLL is delay loaded with the /delayload:[dllname] option and link with delayimp.lib. You can add a library in a .cpp file with

#pragma comment(lib, "delayimp")

which will remove the need to specify it on the linker command line.

I'm not sure what goes in the .pro file to accomplish adding the delayload switch to the linker command.

See this link for the Microsoft docs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top