您的位置:首页 > 编程语言 > Python开发

使用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文件:

#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'
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息