我有一个 C++ 类(class)。它由一个.ccp 文件和一个.h 文件组成。它可以编译(我可以编写一个在 c++ 中成功使用它的主要方法)。如何使用 Cython 包装此类以使其在 Python 中可用?
我已阅读文档但未遵循。他们谈论生成 cpp 文件。当我尝试关注文档时,我已经存在的 cpp 被吹走了......
我打算在 pyx 文件中放入什么?我被告知类定义,但有多少?只是公共(public)方法?
我需要一个 .pxd 文件吗?我不明白何时需要或不需要此文件。
我已尝试在#python IRC channel 中提出这些问题,但无法得到答案。
最佳答案
Cython 通常也用于C,它也可以生成C++ 代码。编译时添加--cplus
标志。
现在,为类创建包装器很简单,与包装结构没有太大区别。它主要不同于声明 extern
, 但这根本没有太大区别。
假设你有一个类(class) MyCppClass
在 mycppclass.h
.
cdef extern from "mycppclass.h":
cppclass MyCppClass:
int some_var
MyCppClass(int, char*)
void doStuff(void*)
char* getStuff(int)
cdef class MyClass:
# the public-modifier will make the attribute public for cython,
# not for python. Maybe you need to access the internal C++ object from
# outside of the class. If not, you better declare it as private by just
# leaving out the `private` modifier.
# ---- EDIT ------
# Sorry, this statement is wrong. The `private` modifier would make it available to Python,
# so the following line would cause an error es the Pointer to MyCppClass
# couldn't be converted to a Python object.
#>> cdef public MyCppClass* cobj
# correct is:
cdef MyCppClass* obj
def __init__(self, int some_var, char* some_string):
self.cobj = new MyCppClass(some_var, some_string)
if self.cobj == NULL:
raise MemoryError('Not enough memory.')
def __del__(self):
del self.cobj
property some_var:
def __get__(self):
return self.cobj.some_var
def __set__(self, int var):
self.cobj.some_var = var
请注意 new
关键字仅在 --cplus
时可用标志已设置,否则使用 malloc
来自 <stdlib.h>
通过外部化它。
另请注意,您无需取消引用指针 (->
) 即可调用该方法。 Cython 跟踪对象的类型并应用适合的类型。
.pxd 文件用于将声明与实现分开,或避免命名空间冲突。想象一下,您想将 Python 包装器命名为 C++ 类。只需在您的 .pxd 文件中输入 extern
声明和 cimport
.pyx 中的 pxd 文件。
cimport my_pxd
cdef my_pxd.SomeExternedType obj
请注意,您不能在 .pxd 文件中编写实现。
关于c++ - 如何用 Cython 包装 C++ 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8933263/