Tchaikov’s Journal

July 3, 2006

SWIG 和指针

Filed under: Python, C++

演示平台需要使用C语言实现的算法。算下来比较成熟的绑定工具就数 SWIGBoost.Python 了。SWIG 是一个通吃型的杀手程序,从 Python 到 Mzscheme 都照顾到了。wxWidgetsPython 绑定就是用的 SWIG。 Boost.Python 则专注于 C++ 和 Python 的互通。考虑到安装的便捷程度和易用性,我还是用了 SWIG。以前在 Windows 上花半个小时,用 jam 编译 Boost,太可怕了。而且这种高阶的 meta programming 不是所有人都能够接受的。嗯,还是 SWIG。SWIG 有直接可以在 Windows 安装的预编译版本,十分方便。用起来也简单。照着这里写一个 interface file:

module example
%include \"typemaps.i\"
int foo(int n, float* OUTPUT, float* OUTPUT);

swig 的文档说的非常明白了。在这里,n是输入参数,两个OUTPUT是用来作为输出的指针。example是 Python 看到的模块名。要编译生成一个 example 模块:

swig -python example.i # 生成 example_wrap.c 和 example.py
gcc -c -fPIC example.c # 编译 foo() 实现所在的源文件
gcc -c -fPIC example_wrap.c -I /usr/include/python2.3
ld -shared example.o example_wrap.o -o _example.so

这时候,example模块只包含了两个文件:example.py 和 _example.so。在 Python 里照常用就可以了。

In [1]: import example
In [2]: example.foo(1)
Out[3]: [4, 1.0, 2.0]

可以注意到,SWIG 把两个输出参数和返回值并成一个 list 返回了。不知道调用的代价会不会很高,先试试看吧。

Comments »

The URI to TrackBack this entry is: http://tchaikov.blogsome.com/2006/07/03/p40/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>


Get free blog up and running in minutes with Blogsome
Theme designed by Jay of onefinejay.com