Qt 加载动态库DLL

来源:互联网 发布:怎么遍历json数组 编辑:程序博客网 时间:2024/05/16 23:38

1. 首先生成DLL,或者有现成的。

#ifndef TEST_H#define TEST_H#include "test_global.h"#include <QString>#include <iostream>

/* 在Windows上,还必须使用__declspec(dllexport)编译器指令从DLL显式导出该函数 */#ifdef Q_OS_WIN#define MY_EXPORT __declspec(dllexport)#else#define MY_EXPORT#endifextern "C"{void hello(void *in, void *out);}#endif // TEST_H#include "test.h"MY_EXPORT void hello(void *in, void *out){    memcpy((char *)out, (char *)in, 512);}


2.调用代码

#include "mainwindow.h"#include <QApplication>#include <QLibrary>#include <QDebug>typedef int (__stdcall *lib_form)(void *, void *);  //声明一个函数类型lib_form dll_hello;bool LoadDll(){    QString input = "hello!";    QString out = "";    char outbuf[512] = {0};    /* 获取路径 */    QString DllPath = "C:/Users/flysea/Documents/test5/MyDebug/test5";    /* 加载函数 */    QLibrary Lib;    Lib.setFileName(DllPath);    if(!Lib.load())    {        qDebug() << "Load fail";        return false;    }    dll_hello = (lib_form)Lib.resolve("hello");    if(!dll_hello)    {        qDebug() << "Lib resolve fail";        return false;    }    /* 执行 */    QByteArray pInput = input.toUtf8();    dll_hello(pInput.data(), outbuf);    out = QString::fromLocal8Bit(outbuf);       //返回值->转换字符格式    qDebug() << out;    return true;}int main(int argc, char *argv[]){    QApplication a(argc, argv);    MainWindow w;    w.show();    LoadDll();    return a.exec();}