C/C++使用dlopen手动加载动态so库
Posted 木大白易
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C/C++使用dlopen手动加载动态so库相关的知识,希望对你有一定的参考价值。
前言
类似于Java中System.load()和System.loadLibrary(),linux也提供了手动加载动态库的方式,就是通过dlopen打开,然后dlsym去获取函数或者变量的符号。
手动加载
C中动态加载
举个例子,在c中打开x264的一个函数:
#include <x264.h>
#include <dlfcn.h>
typedef int (*x264_encoder_encode_func)(x264_t *, x264_nal_t **pp_nal, int *pi_nal,
x264_picture_t *pic_in, x264_picture_t *pic_out);
x264_encoder_encode_func x264EncoderEncodeFunc;
void dl_get_x264_addr()
void *handle = dlopen("libx264.so", RTLD_LAZY);
x264EncoderEncodeFunc = dlsym(handle, "x264_encoder_encode");
//下边可以直接使用x264EncoderEncodeFunc()
c++中动态加载
c++里稍微有点不一样
#include <x264.h>
#include <dlfcn.h>
int (*x264_encoder_encode_func)(x264_t *, x264_nal_t **pp_nal, int *pi_nal,
x264_picture_t *pic_in, x264_picture_t *pic_out);
void dl_get_x264_addr()
void *handle = dlopen("libx264.so", RTLD_LAZY);
x264_encoder_encode_func = reinterpret_cast<int (*)(x264_t *, x264_nal_t **pp_nal, int *pi_nal,
x264_picture_t *pic_in, x264_picture_t *pic_out)>(dlsym(handle, "x264_encoder_encode"));
//下边可以直接使用x264_encoder_encode_func()
以上是关于C/C++使用dlopen手动加载动态so库的主要内容,如果未能解决你的问题,请参考以下文章
Linux C++ libdl.so dlfcn.h使用方法(dlopen()dlsym()dlclose()dlerror())(用于动态链接库操作)(懒加载立即加载)共享库符号动态库