前段时间需要完成多个模块业务,而这些模块的接口都是一样的,于是为了方便管理就把每个模块都根据接口封装成了SO库,这里就留下SO库调用样例
SO库源文件代码:
1 //TestSo.c 2 #include <stdio.h> 3 4 int CommonInterface(char* str, unsigned int strLen) 5 { 6 //deal with ... 7 printf("%s, %d ", str, strLen); 8 return 1; 9 }
编译命令:
gcc -shared -o TestSo.so TestSo.c
使用库代码:
1 //Main.c 2 #include <stdio.h> 3 #include <dlfcn.h> 4 5 typedef int (*CommonInterface_Func)(char* str, unsigned int strLen); 6 7 #define TEST_SO_FILE "/root/test/libtestSo.so" 8 void* soHandle = NULL; 9 10 /* get dynamic library function address, returns 1 success, otherwise fail. */ 11 int getCommonInterfaceFuncAddr(CommonInterface_Func* funcAddr) 12 { 13 // laod dynamic library. 14 soHandle = dlopen(TEST_SO_FILE, RTLD_LAZY); 15 if ( soHandle == NULL ) 16 { 17 printf("dlopen,(%s)", dlerror()); 18 return 0; 19 } 20 // get func addr 21 *funcAddr = (CommonInterface_Func)dlsym(soHandle, "CommonInterface"); 22 if ( *funcAddr == NULL ) 23 { 24 printf("dlsym,(%s)", dlerror()); 25 dlclose(m_soHandle); 26 return 0; 27 } 28 return 1; 29 } 30 31 int main(int argc, char* argv[]) 32 { 33 char* str = "hello so."; 34 CommonInterface_Func funcAddr = NULL; 35 int result = getCommonInterfaceFuncAddr(&funcAddr); 36 37 if (result != 1) 38 { 39 printf("get func address fail. "); 40 return 0; 41 } 42 printf("get func address success. "); 43 result = funcAddr(str, strlen(str)); 44 printf("exec func result : %d ", result); 45 46 return 1; 47 }
编译命令:
gcc -o Main_exec Main.c -ldl
执行:./Main_exec
参考链接:http://www.cnblogs.com/leaven/archive/2010/06/11/1756294.html