gpt4 book ai didi

python - 一种将 C++ 对象传递给 cython 中另一个对象的方法的方法

转载 作者:行者123 更新时间:2023-11-30 05:23:16 26 4
gpt4 key购买 nike

我有两个类(假设最简单的类,实现并不重要)。我的 defs.pxd 文件(带有 cython defs)如下所示:

cdef extern from "A.hpp":
cdef cppclass A:
A() except +

cdef extern from "B.hpp":
cdef cppclass B:
B() except +
int func (A)

我的 pyx 文件(带有 python defs)如下所示:

from cython.operator cimport dereference as deref
from libcpp.memory cimport shared_ptr

cimport defs

cdef class A:
cdef shared_ptr[cquacker_defs.A] _this

@staticmethod
cdef inline A _from_this(shared_ptr[cquacker_defs.A] _this):
cdef A result = A.__new__(A)
result._this = _this
return result

def __init__(self):
self._this.reset(new cquacker_defs.A())

cdef class B:
cdef shared_ptr[cquacker_defs.B] _this

@staticmethod
cdef inline B _from_this(shared_ptr[cquacker_defs.B] _this):
cdef B result = B.__new__(B)
result._this = _this
return result

def __init__(self):
self._this.reset(new cquacker_defs.B())

def func(self, a):
return deref(self._this).func(deref(a._this))

问题是 deref(self._this) 工作正常,但是 deref(a._this) 没有这个错误:

Invalid operand type for '*' (Python object)

如何将一个 python 对象的内部 C++ 对象传递给另一个 python 中的方法?

最佳答案

def func(self, A a):
return # ... as before

您需要告诉 Cython aA 类型(调用时检查类型)。这样它就知道 a._this 并且不会将其视为 Python 属性查找。如果 Cython 在完成时知道类型,您只能访问 cdefed 属性。

关于python - 一种将 C++ 对象传递给 cython 中另一个对象的方法的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39280945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com