当前位置:网站首页 > 技术博客 > 正文

linux运行so文件



 1 #include <iostream>  2 #include <dlfcn.h>  3 #include "test.h"  4 using namespace std;  5  6 //声明函数指针  7 typedef Test* (*so_init)();  8  9 //定义插件类来封装,句柄用完后需要释放 10 struct Plugin{ 11 void *handle; 12 Test *t; 13 14  Plugin():handle(NULL), t(NULL) { } 15 ~Plugin(){ 16 if(t) { delete t; } 17 if (handle) { dlclose(handle); } 18  } 19 }; 20 21 int create_instance(const char *so_file, Plugin &p){ 22 //根据特定的模式打开so文件, 获取so文件句柄 23 //RTLD_NOW:需要在dlopen返回前,解析出所有未定义符号 24 //RTLD_DEEPBIND:在搜索全局符号前先搜索库内的符号,避免同名符号的冲突 25 p.handle = dlopen(so_file, RTLD_NOW | RTLD_DEEPBIND); 26 if (!p.handle) { 27 cout << "Cannot open library: " << dlerror() << endl; 28 return -1; 29  } 30 31 //根据字符串"create"读取库中对应到函数, 并返回函数地址,可以理解为一种间接的“反射机制 32 so_init create_fun = (so_init) dlsym(p.handle, "create"); 33 if (!create_fun) { 34 cout << "Cannot load symbol" << endl; 35  dlclose(p.handle); 36 return -1; 37  } 38 39 //调用方法, 获取类实例  40 p.t = create_fun(); 41 42 return 0; 43 } 44 45 int main(){ 46  Plugin p1; 47  Plugin p2; 48 49 if (0 != create_instance("https://www.cnblogs.com/xudong-bupt/p/libtest_1.so", p1) 50 || 0 != create_instance("https://www.cnblogs.com/xudong-bupt/p/libtest_2.so", p2)){ 51 cout << "create_instance failed" << endl; 52 return 0; 53  } 54 55 p1.t->set(1); //对库1中到全局变量进行设置 56 p2.t->set(2); //对库2中到全局变量进行设置 57 58 //输出两个库中的全局变量 59 cout << "t1 g_num is " << p1.t->get() << endl; 60 cout << "t2 g_num is " << p2.t->get() << endl; 61 return 0; 62 }

版权声明


相关文章:

  • c语言中的实型变量分为两种类型2025-04-04 22:29:59
  • 尺度空间.apk2025-04-04 22:29:59
  • client clientele区别2025-04-04 22:29:59
  • redis 远程连接2025-04-04 22:29:59
  • 进程和线程的相同点2025-04-04 22:29:59
  • win10怎样搜索文件内容2025-04-04 22:29:59
  • sqlldr ora018302025-04-04 22:29:59
  • 什么是红黑树2025-04-04 22:29:59
  • 访问域名已经升级2025-04-04 22:29:59
  • linux监控jvm内存2025-04-04 22:29:59