LINUX C/C++ 動態 載入/引用 函式庫/函數庫(so/dll)「linux_C_so_project」
LINUX C/C++ 動態 載入/引用 函式庫/函數庫(so/dll)「linux_C_so_project」
資料來源: https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/430351/
GITHUB:https://github.com/jash-git/linux_C_so_project
01.LIB_CODE (caculate.c)
#include <stdio.h>
int add(int a,int b)
{
return (a + b);
}
int sub(int a, int b)
{
return (a - b);
}
int mul(int a, int b)
{
return (a * b);
}
int div(int a, int b)
{
return (a / b);
}
02.EXE_CODE (test_so.c)
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
//動態連結庫路徑
#define LIB_CACULATE_PATH "./libcaculate.so"
//函式指標
typedef int (*CAC_FUNC)(int, int);
int main()
{
void *handle;
char *error;
CAC_FUNC cac_func = NULL;
//開啟動態連結庫
handle = dlopen(LIB_CACULATE_PATH, RTLD_LAZY);
if (!handle)
{
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
//清除之前存在的錯誤
dlerror();
//獲取一個函式
*(void **) (&cac_func) = dlsym(handle, "add");
if ((error = dlerror()) != NULL)
{
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
printf("add: %d\n", (*cac_func)(2,7));
cac_func = (CAC_FUNC)dlsym(handle, "sub");
printf("sub: %d\n", cac_func(9,2));
cac_func = (CAC_FUNC)dlsym(handle, "mul");
printf("mul: %d\n", cac_func(3,2));
cac_func = (CAC_FUNC)dlsym(handle, "div");
printf("div: %d\n", cac_func(8,2));
//關閉動態連結庫
dlclose(handle);
exit(EXIT_SUCCESS);
}
03.編譯so
gcc -fPIC -shared caculate.c -o libcaculate.so
04.編譯執行檔
gcc -rdynamic -o main test_so.c -ldl
3 thoughts on “LINUX C/C++ 動態 載入/引用 函式庫/函數庫(so/dll)「linux_C_so_project」”
動態加載 C/C++ SO/DLL
WINDOWS 動態 載入/引用 函式庫/函數庫(so/dll)
LoadLibrary
GetProcAddress
FreeLibrary
BCB創建dll和VS使用dll方法 [VSCallBCBDll]
此篇文章 有完整Code