Search code examples
c++linuxqtshared-librariesdynamic-loading

How to dlsym load QString Function


I'm trying to write a C++ tool using Qt for linux system. my tool using shared lib I'm writing a lib to push data to database. method like that in header file

QString pushdata(QVariantMap params);

this fucion put in lib call libpushdata.so. I would like to load dynamic lib.so I'm using dlfcn.h and method like that:

void *handle;
QString (*pushdata)(QVariantMap*);
handle = dlopen("libpushdata.so", RTLD_LAZY);
if (!handle) {
    fputs(dlerror(), stderr);
    exit(1);
}
pushdata=dlsym(handle,"pushdata");

when build program I get error:

invalid conversion from ‘void*’ to ‘QString ()(QVariantMap)

I search google to how to use dynamic load library and get the instruction like that here and here anyone can show me how to load my method QString pushdata(QVariantMap params) in shared lib. I'm using Eclipse and Centos 6.5, Qt4.8


Solution

  • You can use QLibrary to call functions dynamically. The following example calls a function from a shared library at runtime:

    #include <QLibrary>
    #include <QDebug>
    
    typedef QString (*call_func)(QVariantMap* arg1);
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        QLibrary library( "dynamic_library" );
        library.load();
        if( !library.isLoaded() )
        {
            qDebug() << "Cannot load library.";
            return 0;
        }
        call_func func = (call_func)library.resolve( "pushdata" );
        if(func)
        {
            func(variantMap);
        }
    
        return a.exec();
    }