Size: 2350
Comment:
|
Size: 744
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
'''Pyrex与C++混合编程''' | '''Pyrex''' -- C/C++混合编程支持工具 |
Line 9: | Line 10: |
其实高版本的Pyrex可以与C++混合编程,不过中文社区里好像没有介绍,这也是我写这篇教程的原因。 |
|
Line 14: | Line 13: |
''其实高版本的Pyrex可以与C++混合编程,不过中文社区里好像没有介绍,这也是我写这篇教程的原因。'' |
|
Line 17: | Line 18: |
'''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) { return a+b; }; =>gcc -c test.c 生成test.o =>ar -rsv libtest.a test.o 生成了 libtest.a 静态库 2,我们测试一下这个lib可以用吗? =>vi ttest.c #include <stdio.h> #include "test.h" void main(int argc, void * argv[]) { int c=1; c = tadd(1, 4); printf("c = %d \r\n", c); } =>gcc ttest.c -ltest -L. 生成了a.out ./a.out 结果是: c = 5 证明我们的lib库是可以正常工作的 3,写一个python的模块td,调用它libtest里的tadd()函数 写一个pyx, =>vi td.pyx cdef extern from "test.h": int tadd(int i, int j) def tdadd(int i, int j): cdef int c c=tadd(i, j) return c 就在这行调用的:c=tadd(i, j)了。 编译: =>pyrexc td.pyx 生成 td.c =>gcc -c -fPIC -I/usr/include/python2.4/ td.c 生成td.c =>gcc -shared td.o -ltest -L. -o td.so 生成了td.so。这个就是python可以用的模块so了 安装: =>vi setup.py from distutils.core import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup( name = "PyrexGuide", ext_modules=[ Extension("td", ["td.pyx"], libraries = ["test"]) ], cmdclass = {'build_ext': build_ext} ) =>python setup.py build_ext --inplace 测试: >>> import td >>> dir(td) ['__builtins__', '__doc__', '__file__', '__name__', 'tdadd'] >>> td.tdadd(1,2) 3 呵呵,OK了。 等会再试一试ctypes |
'''061206 列表分享[http://groups-beta.google.com/group/python-cn/t/e5e530a83c136811 一个简单但完整pyrex的例子]''' * [:FeihuTryPyrex:一个简单但完整pyrex的例子] |
Pyrex -- C/C++混合编程支持工具
综述
以前python想用C++混合编程只能通过 Boost 或 Swig 或是 DIY ,不过这三种方法都有些麻烦,不易控制与扩展。
我的教程
ybeetle
060817分享 其实高版本的Pyrex可以与C++混合编程,不过中文社区里好像没有介绍,这也是我写这篇教程的原因。
- 附件:教程所用代码下载 attachment:pyxx.rar
[:YbeetLeTryPyrex:快速尝试Pyrex和C++]
feihu
061206 列表分享[http://groups-beta.google.com/group/python-cn/t/e5e530a83c136811 一个简单但完整pyrex的例子]
[:FeihuTryPyrex:一个简单但完整pyrex的例子]