boost 动态库导出函数,按别名导出

boost 动态库导出函数,按别名导出

文件列表

  1. boost_alias.cpp
  2. madd.cpp
  3. madd.h

源码

  1. boost_alias.cpp
#include <boost/dll/alias.hpp>
#include <boost/dll/shared_library.hpp>
#include<iostream>
#include <dlfcn.h>
#include"madd.h"
using namespace std;

int f1();
int f2();
int f3();
int main(){
	
	f3();
	return 0;
}	

 
int f3(){
  //dlerror();
  void *lib_dl = dlopen("./libmadd.so",RTLD_LAZY);
  if(lib_dl == NULL){
    cout<<"load so error"<<endl;
    return -1;
  }
  int (*pfm)(int  , int ) = NULL;
  
  pfm = (int (*)(int  , int ))dlsym(lib_dl,"madd"); 
  cout<<"pfm ="<<*pfm <<endl;
  
  const char *dlmsg = dlerror();
  if(dlmsg){
    cout<<"load func error"<<endl;
    return -1;
  }
  if(pfm){
    cout<<(*pfm)(2,3)<<endl;
  }
  else {
    cout<&
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C++ 中,可以使用 Boost 的 `boost::dll` 模块来实现动态加载和卸载代码,从而实现更灵活的程序设计和扩展功能。以下是加载动态的基本步骤: 1. 使用 `boost::dll::shared_library` 类加载动态,该类的构造函数接受动态路径和加载选项(如 `boost::dll::load_mode::append_decorations`)。 ```c++ #include <boost/dll.hpp> boost::dll::shared_library lib("MyDll.dll", boost::dll::load_mode::append_decorations); ``` 2. 如果加载成功,可以使用 `lib.get<int(int, int)>("Add")` 函数获取动态导出函数的地址,该函数的模板参数为函数类型,参数为函数名。 ```c++ #include <boost/dll.hpp> typedef int (*PFunc)(int, int); // 定义函数指针类型 PFunc pAdd = (PFunc)lib.get<int(int, int)>("Add"); // 获取函数地址 ``` 3. 调用导出函数。 ```c++ int result = pAdd(1, 2); // 调用函数 ``` 4. 如果需要卸载动态,可以使用 `lib.unload()` 函数释放动态。 ```c++ lib.unload(); // 卸载动态 ``` 需要注意的是,动态中的函数必须使用 `BOOST_SYMBOL_EXPORT` 宏进行导出,例如: ```c++ #include <boost/config/export.hpp> BOOST_SYMBOL_EXPORT int Add(int a, int b) { return a + b; } ``` 同时,动态需要使用 `-DBOOST_ALL_DYN_LINK` 宏进行编译,例如: ```sh g++ -shared -fPIC -o MyDll.dll MyDll.cpp -DBOOST_ALL_DYN_LINK ``` 其中,`-fPIC` 选项表示生成位置无关代码,以便在不同的进程空间中共享。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值