如何在Cython C++容器中存储python对象?

And*_*rge 8 c++ python templates cython

我想用将现有的到Python,使用的C++库.在这种情况下,它是adevs库.

问题是如何使用Cython将Python对象存储在C++容器中?对于引用计数问题,我知道这有点 气馁,但是可以这样做,如果是的话,怎么做?

我知道Gauthier Boaglios类似问题的回答.但是,这并没有解决引用计数的问题,显然,我尝试了以下方法:

让我们说'cadevs.pxd'我有以下代码:

cdef extern from "adevs/adevs_digraph.h" namespace "adevs":
cdef cppclass PortValue[VALUE, PORT]:
    PortValue() except +
    PortValue(PORT port, const VALUE& value) except +
    PORT port
    VALUE value
Run Code Online (Sandbox Code Playgroud)

在'adevs.pyx'中:

from cpython.ref cimport PyObject
cimport cadevs

ctypedef PyObject* PythonObject

cdef class PortValue:
    cdef cadevs.PortValue[PythonObject, PythonObject]* _c_portvalue

    def __cinit__(self, object port, object value):
        self._c_portvalue = new cadevs.PortValue[PythonObject, PythonObject](
            <PyObject *>port, <PyObject *>value
        )

    def __dealloc__(self):
        del self._c_portvalue

    property port:
        def __get__(self):
            return <object>self._c_portvalue.port

    property value:
        def __get__(self):
            return <object>self._c_portvalue.value
Run Code Online (Sandbox Code Playgroud)

然后我进行cythonize并编译

$ cython --cplus -3 adevs.pyx
$ g++ -shared -pthread -fPIC -fwrapv -O2 -Wall -I/usr/include/python3.4m -I../include -lpython3.4m -o adevs.so adevs.cpp
Run Code Online (Sandbox Code Playgroud)

但是在python或ipython中运行

import adevs
pv = adevs.PortValue((1,2), 3)
pv.port
pv.port
Run Code Online (Sandbox Code Playgroud)

崩溃Python显然失去了对(1,2)元组的引用.

小智 0

我不确定绑定到 Cython 这可能很困难,我建议使用 Pybind11,这使得为 C++ 编写 python 包装器(相对)简单(请参阅此面向对象代码的特定示例)。