源码:
https://github.com/haidragon/QtloadSo
在linux中使用dlopen是要额外添加库的,或者在编译的时候要加-ldl
现在我们在qt中创建一个SoMain(so)项目。
和普通项目一样,创建一个窗口项目。运行下确保qt程序能正常运行。
源码:
main.cpp
#include "mainwindow.h"
#include <QApplication>
#include<QMessageBox>
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
修改pro文件
TEMPLATE = app
修改成
TEMPLATE = lib文件
在main.cpp文件中添加运行构造与析构函数 动态库main函数是不会运行的
#include "mainwindow.h"
#include <QApplication>
#include<QMessageBox>
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
void __attribute__ ((constructor)) SoMain(int argc, char *argv[]){
QApplication a(argc, argv);
QMessageBox::about(nullptr, "About", "SoMain");
}
void __attribute__ ((constructor)) SoMain2(int argc, char *argv[]){
QApplication a(argc, argv);
QMessageBox::about(nullptr, "About", "SoMain2");
}
void __attribute__ ((destructor)) SoUnload(int argc, char *argv[]){
printf("SoUnload \n");
}
生成so文件
写个main函数加载它
//#include "mainwindow.h"
//#include <QApplication>
#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char *argv[])
{
void * libm_handle = NULL;
libm_handle = dlopen("/root/Desktop/build-test-Desktop_Qt_5_12_0_GCC_64bit-Debug/libtest.so", RTLD_LAZY );
// QApplication a(argc, argv);
// MainWindow w;
// w.show();
// return a.exec();
}
会依次运行构造与析构函数
构造函数1
构造函数2
析构函数1 这里不能像构造函数一样弹框 应该是没了qt对象了 可以看看qt源码它什么时候释放的QApplication。
现在我们用qt项目加载so文件
新创建一个项目
代码
#include "mainwindow.h"
#include <QApplication>
#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char *argv[])
{
void * libm_handle = NULL;
libm_handle = dlopen("/root/Desktop/build-test-Desktop_Qt_5_12_0_GCC_64bit-Debug/libtest.so", RTLD_LAZY );
// QApplication a(argc, argv);
// MainWindow w;
// w.show();
// return a.exec();
}
运行时会报错找不到符号
在pro文件中加上:
LIBS += -L/lib/x86_64-linux-gnu -ldl
也可以用qt自己封装的加载库函数,但是不太好控制。