在cython中将C ++对象转换为python对象?

时间:2017-06-10 00:40:45

标签: python cython

我的第一个cython计划很难,所以如果我有一个愚蠢的问题,请不要劝阻我。

这是我的例子:

c_foo.h:

// c_foo.h
class foo:
{
    public:
        ....

        std::unique_ptr<2DVector> get_cFoo_unique_ptr(); // Vec2D<T> is a vector of vectors of T
                                                         // std::vector<std::vector<T>>

    private:
        std::unique_ptr<Vec2D> cFoo_unique_ptr; // Vec2D<T> is a vector of vectors of T
}

foo.pyx:     #foo.pyx     进口cython     ......#other import     来自cython.operator cimport unique_ptr as cpp_unique_ptr

cdef extern from c_foo.h:
    cdef cppclass c_foo:
        ...

        cpp_unique_ptr get_cFoo_unique_ptr()


cdef class py_foo:
    cdef c_foo* cFoo

    ...

    def get_Vec2D(self):
        return self.cFoo.get_cFoo_unique_ptr().get()

所以,我在这里尝试做的是从C ++ unique_ptr获取数据并在python 中返回它们。 并且cython抱怨它。

def get_Vec2D(self):
    return self.cFoo.get_cFoo_unique_ptr().get()
----------------------------------------------------------
 foo.pyx:xx:xx: Cannot convert 'T *' to Python object   

另一种尝试是我尝试其他方式来声明向量的cython unique_ptr:

# foo.pyx
import cython
... # other import
from cython.memory cimport unique_ptr as cpp_unique_ptr
from cython.vector cimport vector as cpp_vector

cdef extern from c_foo.h:
    cdef cppclass c_foo:
        ...

        cpp_unique_ptr[cpp_vector[cpp_vector[T]]] get_cFoo_unique_ptr()


cdef class py_foo:
    cdef c_foo* cFoo

    ...

    def get_Vec2D(self):
        return self.cFoo.get_cFoo_unique_ptr().get()

仍然是同样的错误:

Cannot convert 'vector[vector[T]] *' to Python object

所以,我的问题是如何在cython中访问C ++ unique_ptr的数据? 我是否应该通过cython在C ++和python之间传递数据?

由于

1 个答案:

答案 0 :(得分:1)

这种事让我很困惑。我只在C环境中使用Cython,而不是C ++,所以我不知道你的案例中可能存在的其他选项。但我会解释我是如何做到的,并希望这会有所帮助。

您必须在Cython函数的末尾创建Python对象,因为这些是唯一有效的返回值。这意味着,除其他外,您无法返回指针或C数组。例如,假设我有一个计算双数组的Cython函数f:

def f():
    cdef double aa[1000]
    cdef int i
    # ....
    # some calculation that populates aa
    # ....
    # Now I can't just return aa because aa isn't a Python object.
    # I have to convert it to a Python list:
    a = []
    for i in range(1000):
        a.append(aa[i])  # Cython knows how convert one C float to one Python float
    return a