linuxとC 共有ライブラリの動的ロード
ライブラリの動的ロード。
んーー。
○libshared.h
#include <stdio.h> typedef struct { int a; int b; } MyType; int hello2(MyType t,char *buf); int hello(char *buf); >|| ○libshared.c >|cpp| #include <stdio.h> #include "libshared.h" int hello2(MyType type,char *buf) { printf("hello! %s %d %d\n",buf,type.a,type.b); } int hello(char *buf) { printf("hello! %s\n",buf); return 1; }
○dynamicmain.c
#include <stdio.h> #include <dlfcn.h> #include "libshared.h" int main(int argc,char **argv) { void *mod = dlopen("/home/xxx/private/c/libshared.so",RTLD_NOW); if(mod == NULL){ printf("error 1\n"); return 0; } int (*hello)(char *buf); hello = dlsym(mod,"hello"); if(hello == NULL){ printf("error 2\n"); return 0; } hello("****!"); int (*hello2)(MyType type,char *buf); hello2 = dlsym(mod,"hello2"); if(hello2 == NULL){ printf("error 3\n"); } MyType t; t.a = 1; t.b = 3; hello2(t,"xxx"); dlclose(mod); return 0; }
gcc -shared libshared.c -o libshared.so
呼び出されるライブラリをコンパイル。
gcc dynamicmain.c -o dynamicmain -ldl
呼び出してる方のコンパイル。