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

标签 python c++ cython

我有两个类(假设最简单的类,实现并不重要)。我的 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/

相关文章:

python - 为什么 scipy.spatial.ckdtree 运行速度比 scipy.spatial.kdtree 慢

python - 删除 CSV 文件中的最后一个空行

python - 在计数操作python中显示列表中的重复项

python - 如何使用 Cython 将 python 函数作为参数传递给 c++ 函数

cython - 如何从 C 访问 asyncio/uvloop 循环

c++ - cuda中每个 block 一个线程

python - 对 `is` 运算符和字符串感到困惑

python - 使用 Python 将列表导出为 CSV

c++ - 在 C 和 C++ 中包含和链接文件

java - LevelDB 的默认比较器