Ubuntu下測試 C DLOPEN加載動态連結庫
一、add_function.c
#include <stdio.h>
#include <stdlib.h>
int add_function(int i, int j)
{
printf("add_function\n");
return i+j;
};
二、demo_dlopen.c
#include <stdio.h>
#include <stdlib.h> // EXIT_FAILURE
#include <dlfcn.h> // dlopen, dlerror, dlsym, dlclose
typedef int(* FUNC_ADD)(int, int); // 定義函數指針類型的别名
const char* dllPath = "./libdemo.so";
int main()
{
void* handle = dlopen( dllPath, RTLD_LAZY );
if( !handle )
{
fprintf( stderr, "[%s](%d) dlopen get error: %s\n", __FILE__, __LINE__, dlerror() );
exit( EXIT_FAILURE );
}
FUNC_ADD add_func = (FUNC_ADD)dlsym( handle, "add_function" );
printf( "92 add 10 is %d \n", add_func(92,10) );
dlclose( handle );
}
三、執行下面的指令編譯成動态連結so然後執行
gcc -fPIC -shared -o libdemo.so add_function.c
gcc -o demo_dlopen demo_dlopen.c -ldl
