Size: 3752
Comment:
|
Size: 3805
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 7: | Line 7: |
附件:教程所用代码下载 attachment:pyxx.rar |
|
Line 148: | Line 150: |
Pyrex与C++混合编程
以前python想用C++混合编程只能通过 Boost 或 Swig 或是 DIY ,不过这三种方法都有些麻烦,不易控制与扩展。
其实高版本的Pyrex可以与C++混合编程,不过中文社区里好像没有介绍,这也是我写这篇教程的原因。
附件:教程所用代码下载 attachment:pyxx.rar
准备的条件: 1. Python2.4安装 2. Pyrex安装必须是版本 Pyrex-0.9.4.1 才可以与C++编译 3. Dev-C++ 编译器 (版本最好是 4.9.9.2或以上) Linux 下用 g++ 就行 4. 如果windows下必须要先修正 Python24.lib (在我的例程附件中带有修正后的 Python24.lib 文件)
- 修正PythonXX.lib 方法如下:
- 1.拷贝python24.dll 到 C:\Python24\libs 目录下面 2.在命令行模式下,转到Python 的lib 目录下面 3.运行下面命令:
pexports python24.dll >python24.def dlltool --dllname python24.dll --def python24.def --output-lib python24.lib
- 1.拷贝python24.dll 到 C:\Python24\libs 目录下面 2.在命令行模式下,转到Python 的lib 目录下面 3.运行下面命令:
上面的条件要先弄好才能开始玩,要不然别怪我教程不对。
只是编译有C++合成的项目不能用 setup.py 的方法,要手动编译: 假如我的pyrex 文件名是 test.pyx 像这样:
python pyrexc test.pyx (pyrexc文件在 C:\Python24\scripts 下面,要把这个目录在环境变量里设一下。或是复制到你用的目录里)
g++ -c test.c -mno-cygwin -mdll -IC:\Python24\include g++ -mno-cygwin -shared -s test.o -LC:\Python24\libs -lpython24 -o test.pyd
就能通过编绎。
先编写一个C++文件:
/////////////////////////////////////////////////////////////////// // in.h
class AAA{
- int num33; public:
- AAA(){
this->num33 = 10;
return this->num33;
this->num33 = n222;
- AAA(){
};
// 这是创造类的函数 AAA* NewAAA(){
- return new AAA();
}
// 这是析构函数 void DelAAA(void *o){
- AAA* s = (AAA*)o; delete(s);
}
///////////////////////////////////////////////////////////////////
再编写test.pyx 文件将类包含进来
# test.pyx
# 通过 cdef extern 把类在头部声名一次 # 因为C++ class 与 struct 有兼容性所以把类当成 struct 就搞定 cdef extern from "in.h":
- ctypedef struct AAA:
- int (* getNum)() void (* setNum)(int n222)
cdef class PySomeClass:
- cdef AAA *thisptr
def new(self):
- self.thisptr = NewAAA()
def dealloc(self):
- DelAAA(self.thisptr)
- return self.thisptr[0].getNum()
- self.thisptr[0].setNum(n)
运行
import test print test print dir(test) A = test.PySomeClass() A.setNum(99777) print A.getNum()
输出: <module 'test' from 'D:\DTemp\PY~1\test.pyd'> ['PySomeClass', 'builtins', 'doc', 'file', 'name'] 99777 现在基本上就算是研制成功了。。 讲下主要原理: 但在Pyrex声名extern的东西就会原封不运的转换成 C 代码。 C++ 的 class 与 struct 其实是一回事情,在C++编译器与C 混合编译的时侯就一起编译了。 欢迎Python 爱好者一起交流: 我的网名 ybeetle 电邮: [email protected]