Python调用C库
2016-04-30 02:28
441 查看
Python调用C库
Python可以利用ctypes库很方便地调用C的库函数。 C库例程:
# file: a.c
int sum(int a, int b){
int t = 0;
int i = 0;
for(; i < b;i++) t += a;
return t;
}
shell> gcc -fPIC -g -c -Wall a.c && gcc -shared -Wl,-soname,liba.so -o liba.so a.o
Python程序例程:
# file: a.py
import timeit
n=1000000
def s(a,b):
t = 0
for i in xrange(b):
t += a
return t
print s(10,100)
t = timeit.Timer("s(10,20)", "from __main__ import s")
print t.timeit(n)
del s
import ctypes
a = ctypes.cdll.LoadLibrary("./liba.so")
s = a.sum
print s(10,100)
t = timeit.Timer("s(10,20)", "from __main__ import s")
print t.timeit(n)
运行比较:
shell> python2.6 a.py
1000
1.94600701332
1000
0.611714839935
相关文章推荐
- Python按位运算符,字典,运算符优先级的基本总结
- Python - 字母算术谜题
- Python str内部功能介绍
- python 多线程 join 的 细节问题 注意使用事项
- Python开发环境配置
- 如何在MAC 指定文件夹打开终端(terminal)
- python 函数超时装饰器
- python 正则表达式
- python web中models.py中的一些处理
- win下python和opencv安装
- python解决网站的反爬虫策略
- python3.5使用pip安装scrapy时unable to find vcvarsall.bat异常处理
- knn算法python实现
- python解决八皇后问题
- Regular Expression Python
- 基于python的爬虫---自顶向下的设计思想
- python学习5
- windows环境下把Python代码打包成独立执行的exe可执行文件
- python算法基础
- 武sirpython第二讲(1)运算符