歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux下C如何調用動態庫

Linux下C如何調用動態庫

日期:2017/3/1 9:46:41   编辑:Linux編程

首先生成一個測試用的動態庫,代碼如下myso.c

#include <stdio.h>

void Hello()
{
printf("Hello\n");
}

char * Func(char *cstr_name)
{
return cstr_name;
}

編譯成動態庫

gcc -shared -fPIC -o myso.so myso.c

下面程序調用動態庫中的兩個函數

#include <stdio.h>
#include <dlfcn.h>

int main(int argc, char **argv)
{
char *error = NULL;
void *handle = NULL;
void (*Hello)();
typedef char *(*Func)(char *);

//load so file
handle = dlopen("/home/hjchen/myso.so", RTLD_LAZY);
error = dlerror();
if ( error != NULL )
{
printf("Fail to load so file.\n[%s]\n", error);
return -1;
}

//get function address
Hello = (void(*)())dlsym(handle, "Hello");
error = dlerror();
if ( error != NULL )
{
printf("Fail to get function address.\n[%s]\n", error);
return -1;
}

//implement the function
Hello();

//get function address
Func myFunc = (Func)dlsym(handle, "Func");
error = dlerror();
if ( error != NULL )
{
printf("Fail to get function address.\n[%s]\n", error);
return -1;
}
//implement the function
char cstr_name[10] = "hjchen";
char *cstr_return_name = myFunc(cstr_name);
printf("%s\n", cstr_return_name);

//decrease amount of reference
dlclose(handle);

return 0;
}


編譯gcc -ldl -o loadso loadso.c。

需要加上鏈接庫-ldl



整個調用過程主要用到四個函數

dlopen :加載動態庫。參數:(動態庫文件,加載模式);返回:如果加載失敗返回NULL,成功返回一個非空指針。
dlsym:獲取動態庫中函數地址。參數:(dlopen返回的指針,動態庫中的函數名);返回:動態庫中函數指針。
dlclose:將動態庫引用減一,如果達到0就把這個庫從內存中移出去。參數:(dlopen返回的指針).

dlerror:獲取報錯信息。返回:char*類型的錯誤信息。

Copyright © Linux教程網 All Rights Reserved