使用SWIG轻松编写Python扩展
【转至:http://hi.baidu.com/iceboy_/blog/item/554e3828ef7bd8e299250a99.html 】
偶然间翻Python文档时,发现提及一个叫SWIG的东西,上官网一看,是一个能解析C/C++代码并生成Perl/PHP/Python/TCL/Ruby等语言扩展的小工具。一时兴起在Windows环境下试验了一遍并记录。
首先创建foo.h和foo.c,分别声明和定义一个叫hello的函数:
foo.h:
extern void hello(void);
foo.c:
#include <stdio.h>
void hello(void)
{
printf("Hello world!\n");
}
然后编写swig接口(interface)文件foo.i:
%module swigtest
%include "foo.h"
接着,调用swig来生成wrapper,foo_wrap.c和swigtest.py:
swig -python foo.i
最后,使用VC的编译器进行编译:
cl /Fe_swigtest.pyd /LD foo.c foo_wrap.c c:\python27\libs\python27.lib /Ic:\python27\include
将生成的swigtest.py和_swigtest.pyd复制到c:\python27\DLLs和c:\python27\Lib,即完成。
测试:
C:\Users\iceboy>python
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import swigtest
>>> swigtest.hello()
Hello world!
----- 华丽的分割线 -----
将printf替换成int 3,给cl加上/Zi参数生成pdb,得到华丽截图一张: