用python ctypes调用动态链接库

ctypes is very cool! Great piece of work.
           - Just van Rossum

ctypes使得python能够直接调用c语言开发的动态链接库,非常强大。
为了使用CTypes,你必须依次完成以下步骤:
    * 编写动态连接库程序
    * 载入动态连接库
    * 将Python的对象转换为ctypes所能识别的参数
    * 使用ctypes的参数调用动态连接库中的函数

来个简单的实例吧:

1. 编写动态链接库

C代码   收藏代码
  1. // filename: foo.c  
  2.   
  3. #include <stdio.h>  
  4. char* myprint(char *str)  
  5. {  
  6.     puts(str);  
  7.     return str;  
  8. }  
  9.   
  10. float add(float a, float b)  
  11. {  
  12.     return a + b;  
  13. }  

以上foo.c代码,linux下编译为动态链接库文件,命令是:
Shell代码   收藏代码
  1. gcc -fPIC -shared foo.c -o foo.so  


2. ctypes调用

Python代码   收藏代码
  1. #!/usr/bin/env python  
  2. # FILENAME: foo.py  
  3.   
  4. from ctypes import *  
  5.   
  6. foo = CDLL('./foo.so')  
  7.   
  8. myprint = foo.myprint  
  9. myprint.argtypes = [POINTER(c_char)] # 参数类型,为char指针  
  10. myprint.restype = c_char_p # 返回类型,同样为char指针  
  11. res = myprint('hello')  
  12. print res  
  13.   
  14. add = foo.add  
  15. add.argtypes = [c_float, c_float] # 参数类型,两个float(c_float内ctypes类型)  
  16. add.restype = c_float  
  17. print add(1.34.2)  


文档请参考 http://docs.python.org/library/ctypes.html

3. 查找链接库

Python代码   收藏代码
  1. >>> from ctypes.util import find_library  
  2. >>> find_library("m")  
  3. 'libm.so.6'  
  4. >>> find_library("c")  
  5. 'libc.so.6'  
  6. >>> find_library("bz2")  
  7. 'libbz2.so.1.0'  
  8. >>>  


调用libc里的printf:
Python代码   收藏代码
  1. #filename: printf_example.py  
  2.   
  3. import ctypes  
  4. from ctypes.util import find_library  
  5.   
  6. printf = ctypes.CDLL(find_library("c")).printf  
  7.   
  8. printf("hello, world\n"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值