Loading function from a DLL



  • Hi there!

    I am trying to load some DLL's functions, but I am obviously doing something wrong.

    Here is my code :

    //MainWindow.cpp
    #include "MainWindow.h"
    Q_DECLARE_METATYPE(QCameraInfo)
    
    MainWindow::MainWindow()
    {
        m_Plugin_HModule2	= NULL;
        pPluginSetAutoWhiteBalance	= NULL;
    
        // try to load library
        m_Plugin_HModule2 = LoadLibrary("D:\\X.dll");
    
        // load function addresses
        pPluginSetAutoWhiteBalance	= (pfApiPluginSetAutoWhiteBalance)GetProcAddress(m_Plugin_HModule2, "X_SetAutoWhiteBalance")
    
    //MainWindow.h
    #include <QMainWindow>
    
    #include <windef.h>
    #include <winbase.h>
    #include <windows.h>
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        MainWindow();
        ~MainWindow();
    
        typedef BOOL (*pfApiPluginSetAutoWhiteBalance) (bool);
    
    protected:
        HMODULE                            m_Plugin_HModule2;
        pfApiPluginSetAutoWhiteBalance     pPluginSetAutoWhiteBalance;
    
    

    I tried to do what @ludde said here but it dont work for me, even if I delete the "-L" everywhere. I dont know how to load my libraries...
    I did my .def and .lib following the Dark Falcon's answer here.

    I have to say, I am really novice.

    Have a nice day !


  • Qt Champions 2016

    Hello,
    Is there any special reason as to why you're trying to load the library at runtime? You could use QLibrary to do it in a portable manner, however I'd advice load-time linking.

    Kind regards.



  • Hi @kshegunov, and thank you for your answer !

    I have no reason to load the library at runtime. What is the difference between load and runtime in facts ? Except the loading timing.

    Have a nice day, and thanks again for your help.


  • Qt Champions 2016

    @Suji
    Hello,
    There aren't much differences except for a pile of (additional) problems when you do it at runtime. When you load the library at runtime you have to do what the loader will ordinarily do for you, namely to resolve the symbols. Besides the insane amounts of error handling you need to do, because using a symbol that's wrongly resolved (e. g. differences in the function prototype) will cause crashes, you'd also need to make sure the library exists in the first place, and so on ... If you simply leave this to the loader it'll complain before your app starts if something is wrong, so you could fix that before deployment. Loading libraries at runtime is the way to have plugins, as they're not known to the linker when the application compiles, but Qt provides QPluginLoader for that purpose.

    Kind regards.



  • @kshegunov

    Thank you for this very detailed answer, I appreciate it so much.

    So if I want to proceed at the load-time, and if I understand what you said, should I have to use the "loadHints : LoadHints" function ?

    Good afternoon !


  • Qt Champions 2016

    @Suji
    Hello,
    Well, not really. You have to link the library to your project. So suppose you have the headers somewhere, the .lib file (only on windows) and the .dll. The .dll and .lib go in the folder where your application is built. The headers you add to your project with:

    INCLUDEPATH += ./some/path/to/libreary/headerfiles
    

    And you tell qmake to do the linking with:

    LIBS += -L./path/to/the/lib/file -lname
    

    This should suffice to have it working.

    Now, what exactly is X.dll in your example, and do you have the .lib file and the headers that go with it? Was it built with Qt?

    Kind regards.



  • Hi again @kshegunov

    OK, I'll try this. When you talk about "the headers", which are they ?

    The X.dll is a DLL built in VS2013 by a company, they gave me a device + example code and the dll. I'm trying to import the device's functions from this dll in my own soft, in order to pilot the device through their functions. I'm building my own soft because I want to master all which is inside the software, and for more clarity because I'm a rookie. ;)

    I did the .lib and .def from the dll like this :
    http://stackoverflow.com/questions/9946322/how-to-generate-an-import-library-lib-file-from-a-dll

    (sorry for the long link! But bold, link buttons etc... doesnt work)

    Thanks for your help and your patience.

    edit : I have the header you're talking about, didn't know I had to bring it with the dll. Should I include the X.h into my MainWindows.cpp so ? I though all definitions etc was included in the .lib or .dll...


  • Qt Champions 2016

    @Suji
    Okay, so provided you have the header(s), the lib and the dll you put the lib and dll where your application is residing (usually the build folder when developing). Then you #include the header(s) where you want to use the functions that come from the dynamic library and finally you add the linker flags to your .pro file telling what library/ies have to be linked and where to search for the header(s) you're using. After all that you're ready to build your application.

    More concretely:

    1. Suppose your project is in C:/myproject and the application is built in C:/myproject/bin-debug
    2. Let's say the library is called libExternalLibrary.dll with corresponding .lib file libExternalLibrary.lib and you have a header that's in C:/external_library/external_library.h.
    3. You copy libExternalLibrary.dll and libExternalLibrary.lib in C:/myproject/bin-debug
    4. You open your project file (the one that has a .pro extension) that is inside C:/myproject and add the following to it:
    INCLUDEPATH += C:/external_library
    LIBS += -L. -lExternalLibrary
    
    1. In your code, where you want to use the library functions you include the header (at the top):
    #include <external_library.h>
    

    And then you can use the functions that are declared in that header (and defined in the dynamic library).

    I hope this helps.
    Kind regards.



  • So fine ! Thanks a lot @kshegunov ! Your answers are so so clear, I love it!

    I want to ask you something : why I have to do this instead of simply add in my MainWindow.h the prototype of my function which is on my X.h ?

    //MainWindow.cpp
    
    #include <MainWindow.h>
    #include <X.h>
    Q_DECLARE_METATYPE(QCameraInfo)
    
    QLibrary myLib("path\\to\\X.dll");
    
    ParametersDialog::ParametersDialog()
    {...}
    
    void MainWindow::activateSetAutoWhiteBalance()
    {
       MyPrototype funcSetAutoWhiteBalance = (MyPrototype) myLib.resolve("X_SetAutoWhiteBalance");
        if (funcSetAutoWhiteBalance)
           funcSetAutoWhiteBalance(TRUE);
    }
    
    //MainWindow.h
    
    #include <QLibrary>
    
    class MainWindow: public QMainWindow
    {
        Q_OBJECT
    
    public:
        MainWindow();
        ~MainWindow();
    
    public slots:
        void activateSetAutoWhiteBalance();
    
    

    (The activateSetAutoWhiteBalance function is connected to a QcheckBox)

    //X.h
    #include <windows.h>
    
    typedef BOOL (*MyPrototype) (bool );
    

    I really don't understand why using the .dll, .lib etc... Is there something more special inside the dll I dont understand ?


  • Qt Champions 2016

    Hello,
    Firstly, the resolve method has some limitations as noted in the documentation. Secondly, including the vendor header will ensure function prototypes match, which is important! And lastly, this line:

    #include <windows.h>
    

    is windows specific, meaning that if the vendor library actually has different variants for different OS-es your header will not work on anything but windows. Now, I want to make a step back and elaborate on the second point.

    Consider that in the library someone has put a function like this:

    extern "C" __declspec(dllexport) void someFunction(int);
    

    if you declare that in your own header as this:

    void someFunction(int, char);
    

    and then make the QLibrary::resolve call (which will succeed!), you're in a big trouble. Calling that function as:

    someFunction(0, 10);
    

    will cause all kinds of weird and unexpected behavior (crashes included). So even if you're loading the library at runtime, use the vendor's header(s)!

    ADDENDUM:
    Sorry for the edits, it's been years since I've actually developed on windows.

    Kind regards.



  • Hi again @kshegunov !

    Another very clear answer. I appreciate it so much ! If only I could have a programing teacher like you... :)

    Thanks a lot for all the time you took for me, and your patience.

    Have a very nice day !


  • Qt Champions 2016

    @Suji
    You flatter me sir, thank you! I try, although not always succeed. :)



  • hi @kshegunov & @Suji ,

    I have question , hopefully a valid question :)

    @Suji Said: The X.dll is a DLL built in VS2013 by a company,

    @kshegunov If @Suji is working with Qt Creator , then the .dll built by VS 2013 will work inside the program built by Qt Creator?

    I am sorry, if it is not related question here.


  • Qt Champions 2016

    @Ni.Sumi
    Hello,

    I have question , hopefully a valid question

    It is a valid question. It will work no matter the compiler used for building the external library. This is because he's resolving the symbols at runtime (and they are exported as C-linkage, meaning no symbol decorations). C-linkage functions symbol names have the the same structure on any compiler (at least they're supposed to), so he could as well be linking it and it shouldn't cause a problem.
    So when QLibrary::resolve is called, an address (hopefully) is found in the library that correspond to the name provided as a parameter to the function, and this address is manually cast to a function pointer type. This is the scary part, because any misstep with the casting is (usually) fatal for the program. Then, when invoking the resolved function, you do that through the pointer.
    Basically, what you do, is what the loader of the corresponding OS would have done - load the binary in memory and map the symbols (thus getting an address).

    Kind regards.



  • @kshegunov Okay. I understand it. Thanks for the time and explanation.


  • Qt Champions 2016

    @Ni.Sumi
    It's no hassle at all. I've corrected a grammar mistake in the post, but the meaning should remain the same. :)

    Kind regards.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.