问题描述
cdef extern from "Foo.h":
cdef cppclass Bar:
pass
cdef class PyClass:
cdef Bar *bar
def __cinit__(self, Bar *b)
bar = b
这将总是给我类似的东西:
无法将Python对象参数转换为类型'Bar *'
This will always give me something like:
Cannot convert Python object argument to type 'Bar *'
是否有一种方法可以完成此操作,还是我需要从 Bar
对象中提取所有内容,创建等效的Python,并通过它放入,然后在 PyClass
中重建它?
Is there a way to accomplish this, or do I need to extract everything from a Bar
object, create a Python equivalent, pass it in, then reconstruct it in PyClass
?
推荐答案
尝试将带有结构的C代码包装为python类的问题。问题似乎在于,包括 __ init __
和 __ cinit __
在内的特殊函数必须声明为 def
,而不是 cdef
。这意味着可以从普通的python调用它们,因此有效地忽略了类型参数,并将所有内容都视为对象。
I came across this problem trying to wrap C code with structs as python classes. The issue seems to be that "special" function including __init__
and __cinit__
must be declared as def
rather than cdef
. This means that they can be called from normal python, so the type parameters are effectively ignored and everything is treated as object.
在JF Sebastian的回答中,解决方法不是包装-double是基本的数字类型,因此C / C ++类型和Python对象之间存在默认转换。 Czarek的答案基本上是正确的-您需要使用伪造的构造函数,并使用全局函数。不能使用@staticmethod装饰器,因为它们不能应用于cdef函数。在提供的原始示例中,答案看起来更简单。
In J.F. Sebastian's answer the fix is not the wrapping - a double is a basic numeric type and so there is a default conversion between the C/C++ type and the Python object. Czarek's answer is basically correct - you need to use a fake constructor idiom, using a global function. It is not possible to use a @staticmethod decorator as they cannot be applied to cdef functions. The answer looks simpler on the original example provided.
cdef extern from "Foo.h":
cdef cppclass Bar:
pass
cdef class PyClass:
cdef Bar *bar
cdef PyClass_Init(Bar *b):
result = PyClass()
result.bar = b
return result
这篇关于将C ++指针作为参数传递给Cython函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!