加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Linux下动态库so的生成与使用

(2012-07-09 11:25:09)
标签:

linux

动态库

so

生成

使用

杂谈

一.  编写个C文件:test.c

 

  1. #include<stdio.h>  
  2. // file test.c  
  3. int say()  
  4.  
  5.     printf("Hello, Linux so\n");  
  6.     return 0;  
  7.  
  8.   
  9. int add(int x, int y)  
  10.  
  11.     return x+y;  
  12.  

二. 编译成动态库 .so :

 

 

  1.  gcc -shared -o test.so test.c  
  2. /usr/lib/gcc/x86_64-pc-linux-gnu/4.5.3/../../../../x86_64-pc-linux-gnu/bin/ld: /tmp/cc3GkPar.o: relocation R_X86_64_32 against `.rodata' can not be used when making shared object; recompile with -fPIC  
  3. /tmp/cc3GkPar.o: could not read symbols: Bad value  
  4. collect2: ld returned exit status  

出错了,说是要加个 -fPIC 参数(编译成位置无关代码,不然你的程序在别的地方肯可能运行不了):

 

 

  1. gcc -fPIC -shared -o test.so test.c  

OK,成功!

 


三.  C语言中使用使用该动态库(test.so)

1. 编写C file

 

  1. #include<stdio.h>  
  2. // file: myso.c  
  3. int main()  
  4.  
  5.     say();  
  6.     printf("%d\n",add(3+4));  
  7.     return 0;  
  8.  

2. 编译

 

 

  1. gcc -o myso myso.c /root/test.so  

 

3. 运行

 

  1. ./myso  
  2. Hello, Linux so  
  3. 1697202183  

结果明显不正确,3+4 怎么会是 1697201283 ?  原来,add(3+4) 参数传错了 !!

 


四. Python中使用

1. 编写Python 文件

 

  1. #!/usr/bin/python  
  2. from ctypes import  
  3.   
  4. myso cdll.LoadLibrary('/root/test.so' 
  5.   
  6. myso.say()  
  7.   
  8. add myso.add  
  9. add.argtypes [c_int, c_int]    #传入参数类型  
  10. add.restype c_int              #返回值类型  
  11.   
  12. print add(2,3 

2. 使用

 

 

  1.  python myso.py  
  2. Hello, Linux so...  
  3. 5  

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有