Adding executables as resources of a Qt applicatio

2019-02-25 16:24发布

问题:

This question already has an answer here:

  • How do I embed a binary executable (to be executed at runtime) in a Qt program? 4 answers

I've got an external command line executable "program.exe" that makes use of a DLL "program.dll". I would like to embed these two files as resources in my Qt application. Then later, I need to be able to run program.exe from my application. Can it be done with Qt? In particular, can executables and DLLs be added as resources?

回答1:

You can add them as resources, but you won't be able to execute your "program.exe" directly from the resource, at this is a pure Qt system that the underlying OS won't understand.

What you would need to do at execution time is to copy it (with the .dll) from the resources to a temporary location and execute from there.

Obviously, as @webclectic pointed out, this is not a proper approach. Unless there are imperious reason to do that, the right way is to create a package (.msi, .rpm depending of the target OS) with those executables and deploy them that way.



回答2:

In particular, can executables and DLLs be added as resources?

Yes they can, if you add an executable to the qrc file you will notice that the size of your Qt application will be increased by the size of the added resource executable.

But do you really want to do something like this? I have never tried to do something similar but I doubt if this is possible. The system will not be able to read the executable from your resources. The execution of an executable is system specific and the system needs to be able to find the file to be executed. I suppose that on the startup of your application you could copy the executable to a temp dir and call it from there. On application exit you should delete these files.

Personally I would not follow such an approach. Its much simpler and elegant (IMHO) to create an installer that would copy all necessary executables/dlls in the application folder.



回答3:

Binaries could be added as resources and like others have stated extracted to a temporary location to be executed from there. This is similar to how self-extracting installers work.

However it is also possible to directly use them without saving them to a temporary location by writting a custom DLL loader.

I'm not sure but I think executables could be loaded the same way and started by forking. But I think the resulting process would be different compared to when it is started directly from the hard-drive.

I have seen source-code of applications that does exactly this, however it is non-trivial and requires knowledge of low-level stuff. If someone has good resources on how to achieve this, please add them.