Pyrex与C++混合编程 TableOfContents

综述

以前python想用C++混合编程只能通过 Boost 或 Swig 或是 DIY ,不过这三种方法都有些麻烦,不易控制与扩展。

其实高版本的Pyrex可以与C++混合编程,不过中文社区里好像没有介绍,这也是我写这篇教程的原因。

我的教程

ybeetle

060817分享

feihu

061206 列表分享

坐以论道,起而行之,先写一个简单但完整的例子来测试pyrex调用已有lib库法。 环境:ubuntu 6.06,python 2.4.3 参考:http://ldots.org/pyrex-guide/

1,先生成简单的lib: =>vi test.h int tadd(int a, int b);

=>vi test.c #include "test.h" int tadd(int a, int b) {

};

=>gcc -c test.c

=>ar -rsv libtest.a test.o

2,我们测试一下这个lib可以用吗? =>vi ttest.c #include <stdio.h> #include "test.h" void main(int argc, void * argv[]) {

}

=>gcc ttest.c -ltest -L.

证明我们的lib库是可以正常工作的

3,写一个python的模块td,调用它libtest里的tadd()函数

写一个pyx, =>vi td.pyx cdef extern from "test.h":

def tdadd(int i, int j):

就在这行调用的:c=tadd(i, j)了。

编译: =>pyrexc td.pyx

=>gcc -c -fPIC -I/usr/include/python2.4/ td.c

=>gcc -shared td.o -ltest -L. -o td.so

安装: =>vi setup.py from distutils.core import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup(

)

=>python setup.py build_ext --inplace

测试: >>> import td >>> dir(td) ['builtins', 'doc', 'file', 'name', 'tdadd'] >>> td.tdadd(1,2) 3

呵呵,OK了。

等会再试一试ctypes

反馈