dlopen实践

来源:互联网 发布:云计算是什么意思 编辑:程序博客网 时间:2024/05/17 03:10

linux上,使用dlopen dlsym等api来实现对动态库api的调用。非常方便。下面把简单的实践写下来:

 

首先:写个动态库文件,因为只需要dlopen,所以不需要头文件。:

test.c


 

#include <stdio.h>

#include <dlfcn.h>

int test(void)
{
 int a = 0;
 int b =1;
 return (a+b);
}
typedef struct AABB{
 int a;
 char* b;
}*PAB;
void test2(PAB p)
{
 printf("%s,%d\n",p->b,p->a);
}
int g_var = 100;
int test3(int a,int*b)
{
 printf("test2,g_var =%d",g_var);
 printf("a,*b,%d,%d",a,*b);
 return (a+*b);
}

 

int main(int argc,char** argv)
{

 return 1;
}

 

gcc  -c -fpic test.c

gcc -shared -lc  -o test.so  test.o

main.c

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

typedef struct AABB{
 int a;
 char* b;
}*PAB,AB;
typedef int (*CALLBACK)(void);
typedef void (*CALLBACK2)(PAB p);
typedef int (*CALLBACK3)(int a,int*b);
int main(int argc,char** argv)
{
 void *handle;
 //int myTest(void);
 char * error;
 handle = dlopen("./test.so", RTLD_LAZY);
 if(!handle){
  printf("%s-------\n", dlerror());
  return 0;                
  //exit(EXIT_FAILURE);

 }
 printf("succeed\n");
  dlerror(); 
 CALLBACK myTest;
 CALLBACK2 myTest2;
 CALLBACK3 myTest3;
 int* g_test;
 g_test = (int* )dlsym(handle, "g_var");
 printf("%d,test",*g_test);
 *g_test = (*g_test) +100;
  //CALLBACK myTest = (int (*)())dlsym(handle, "test");
 *(void **)(&myTest) = dlsym(handle, "test");
 myTest2 = (void (*)(PAB))dlsym(handle, "test2");
 myTest3 = (int (*)(int,int*))dlsym(handle, "test3");
 if(myTest == NULL)
  printf("null get!\n");
 if(myTest2 == NULL)
  printf("null2 get!\n");
 if(myTest3 == NULL)
  printf("null3 get!\n");
 (*myTest)();
 AB ab;
 ab.a = 1;
 char a[10] = "12345\n";
 ab.b =&a;
 (*myTest2)(&ab);
 int abc =1;
 int *pabc = (int *)malloc(sizeof(int*));
 *pabc = 5;
 (*myTest3)(abc,pabc);
 printf("%d===",*pabc);
  printf("%d\n", (*myTest)());
 return 1;

}

gcc -rdynamic -o main main.c -ldl

原创粉丝点击