前言
类似于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");
}
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"));
}
|