我是在windows中安装了EPD的python安装包,然后看了一下swig的官方文档试了一下,发现很方便
一、假设有如下c文件
/* File : example.c */ #include <time.h> double My_variable = 3.0; int fact(int n) { if (n <= 1) return 1; else return n*fact(n-1); } int my_mod(int x, int y) { return (x%y); } char *get_time() { time_t ltime; time(<ime); return ctime(<ime); }二、现在想在python中使用它,可以很容易使用swig来编写c语言扩展模块
编写如下的swig接口文件example.i ,和example.c保存在同一目录下
/* example.i */ %module example %{ /* Put header files here or function declarations like below */ extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); %} extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time();三、编写如下的DOS批处理文件,命名为BuilderInstall.bat,也放在同一目录里面
swig -python example.i gcc -shared example.c example_wrap.c -IC:/python27/include -LC:/python27/libs -lpython27 -o _example.pyd xcopy *.py* C:/Python27/Lib/site-packages/然后运行(双击该文件即可)BuilderInstall.bat,完成!
四、测试模块。下面可以再python中使用它了:
>>>import _example #注意使用swig编写的接口模块前面都有下划线_ >>>_example.My_variable 3.0 >>>_example.fact(5) 120 >>>_example.get_time() 'Fri Jul 01 16:12:20 2011' >>>