使用SWIG对Python进行扩展
2010-06-22 14:11
639 查看
1.为什么要进行扩展?
按照《core python》,原因有三:
i)添加额外(非python内置)的功能;
ii)提高性能;
iii)保持源码的相对私密。
2.如何进行扩展?
我首先按照《core python》第22章的内容进行的,但是结果不对,在安装setup.py文件时总是出错,又不知从何查起。在这章后面介绍了SWIG这个项目,而后又在啄木鸟社区上看到一个提到说这个是最简单的方法。于是就去SWIG官网上进行学习。
SWIG是用于将c代码(函数)方便地加入到Tcl,Python,Java和C#中去的工具,目前官网上提供的版本是2.0.0,下载解压缩之后安装即可使用。
#./configure && make && make install
之后使用SWIG进行python扩展的具体步骤如下:
a)首先编写你的c函数,比如如下创建一个test.c文件:
b)编写接口文件test.i:
c)编译:
d)All is Done! 现在可以测试一下:
按照《core python》,原因有三:
i)添加额外(非python内置)的功能;
ii)提高性能;
iii)保持源码的相对私密。
2.如何进行扩展?
我首先按照《core python》第22章的内容进行的,但是结果不对,在安装setup.py文件时总是出错,又不知从何查起。在这章后面介绍了SWIG这个项目,而后又在啄木鸟社区上看到一个提到说这个是最简单的方法。于是就去SWIG官网上进行学习。
SWIG是用于将c代码(函数)方便地加入到Tcl,Python,Java和C#中去的工具,目前官网上提供的版本是2.0.0,下载解压缩之后安装即可使用。
#./configure && make && make install
之后使用SWIG进行python扩展的具体步骤如下:
a)首先编写你的c函数,比如如下创建一个test.c文件:
#include <stdio.h> #include <stdlib.h> #include <time.h> void func (int n ) { printf("This is hello message came from C src!"); printf("Let me show u something:/n"); int i=0; for(i=1;i<n;i++){ int j=1; for(j=1;j<i+1;j++) printf("%d*%d = %2d ", j, i, i*j); printf("/n"); } printf("Did u enjoy it?/nBye,Bye, have fun @.@!/n"); } char * get_time(){ time_t ltime; time(<ime); return ctime(<ime); }
b)编写接口文件test.i:
%module test1 %{ /*Put header files here or function declarations like below*/ extern void func(int n); extern char * get_time(); %} extern void func(int n); extern char * get_time();
c)编译:
#swig -python test.i #gcc -c test.c test_wrap.c -I/usr/include/python2.6 #ld -shared test.o test_wrap.o -o _test.so
d)All is Done! 现在可以测试一下:
[moldao@moldao swigtest2]$ python Python 2.6.2 (r262:71600, Jan 25 2010, 18:46:45) [GCC 4.4.2 20091222 (Red Hat 4.4.2-20)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import test >>> dir(test) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic', '_test', 'func', 'get_time'] >>> test.func(5) This is hello message came from C src!Let me show u something: 1*1 = 1 1*2 = 2 2*2 = 4 1*3 = 3 2*3 = 6 3*3 = 9 1*4 = 4 2*4 = 8 3*4 = 12 4*4 = 16 Did u enjoy it? Bye,Bye, have fun @.@! >>> test.get_time() 'Tue Jun 22 14:09:25 2010/n'
相关文章推荐
- 使用swig进行C/C++对Python的扩展
- centos7下使用swig扩展python接口来调用c++ 实现声纹识别
- 使用SWIG轻松编写Python扩展
- 在VC++6.0中使用swig生成Python扩展的配置
- 使用swig为python添加c扩展总结
- 使用SWIG和Python对C/C++进行单元测试(二)
- 使用SWIG来扩展Python
- 使用SWIG实现C++扩展Python
- 使用swig实现C++的python扩展功能
- Python使用pandas扩展库DataFrame对象的pivot方法对数据进行透视转换
- 使用SWIG和Python对C/C++进行单元测试(一)
- 使用swig实现C++的python扩展功能
- 使用SWIG和Python对C/C++进行单元测试
- Python使用pandas对数据进行差分运算
- Python使用pyinstaller进行打包报错
- 使用C语言扩展Python(一)
- ArcGIS教程:使用 Nibble、收缩和扩展功能对区域进行概化
- Python编程使用NLTK进行自然语言处理详解
- 飘逸的python - 使用图像匹配SIFT算法进行LOGO检测
- 使用PCA + KNN对MNIST数据集进行手写数字识别 python