访问c++;通过cython从python获取向量/数组 我用Cython包装C++程序,想从Python中提供这个程序的矢量。< /P>

访问c++;通过cython从python获取向量/数组 我用Cython包装C++程序,想从Python中提供这个程序的矢量。< /P>,python,vector,cython,wrapper,python-extensions,Python,Vector,Cython,Wrapper,Python Extensions,我已经为向量编写了一个getter方法,除了返回一个数据副本之外,它工作得很好: # in cython from libcpp.vector cimport vector cimport numpy as np cdef np.ndarray[double] vector_to_double_arr(vector[double] vec): cdef double[::1] arr = <double [:vec.size()]>vec.data() return

我已经为向量编写了一个getter方法,除了返回一个数据副本之外,它工作得很好:

# in cython
from libcpp.vector cimport vector
cimport numpy as np

cdef np.ndarray[double] vector_to_double_arr(vector[double] vec):
    cdef double[::1] arr = <double [:vec.size()]>vec.data()
    return np.asarray(arr)

def get_variable()
    return vector_to_double_arr(my_c_vector) # my_c_vector is a global variable defined elsewhere

过去,我通过先创建NUMPY数组并在C++内部操作数据来规避这个问题。然而,现在我必须处理一个预先存在的向量

我曾想过直接返回memoryview:

cdef np.ndarray[double] vector_to_double_arr(vector[double] vec):
    cdef double[::1] arr = <double [:vec.size()]>vec.data()
    return arr 
我按如下方式访问指针:

cdef MyClass()
    ...
    @property
    def myArray(self):
        return array_from_ptr(myArrayPointer, myArrayPointerLength, np.NPY_FLOAT64)
从Python访问属性工作得很好,但是只要我更改数组中的任何值(也可以),程序就会停止

m = MyClass()
print(m.myArray) # prints what it is supposed to print
m.myArray[0] = 1 # works
print(m.myArray) # prints what is expected, but terminates the program after freeing the freeing the pointer.
...

当我删除上面代码块中的最后一条print语句时,一切仍然正常。为什么?我很困惑。我能做些什么来解决这个问题?

您可以为vector实现缓冲协议,或者使用numpy数组等。例如,只需对std::vector稍作更改即可包装
std::vector
。诚然,对于2D的情况,但使其成为1D只需要对您的应用程序进行相当小的更改part@ead感谢您对相关问题的解决方案。但是,当我更改数组中的值时,我遇到了一个奇怪的行为(请参阅更新的问题)。你们知道为什么吗?你们的内存可能是属于std::vector的,一旦vector被删除,你们就会得到一个悬空的指针。MemoryAnny不应该在向量中保存指向内存的指针,而应该保存向量本身。@ead要清楚,上面我已经尝试为
double*
实现一个包装器。您的解释仍然适用吗?您可以为vector实现缓冲协议,或者使用例如numpy数组。例如,只需对std::vector稍作更改即可包装
std::vector
。诚然,对于2D的情况,但使其成为1D只需要对您的应用程序进行相当小的更改part@ead感谢您对相关问题的解决方案。但是,当我更改数组中的值时,我遇到了一个奇怪的行为(请参阅更新的问题)。你们知道为什么吗?你们的内存可能是属于std::vector的,一旦vector被删除,你们就会得到一个悬空的指针。MemoryAnny不应该在向量中保存指向内存的指针,而应该保存向量本身。@ead要清楚,上面我已经尝试为
double*
实现一个包装器。那么你的解释仍然适用吗?
cdef MyClass()
    ...
    @property
    def myArray(self):
        return array_from_ptr(myArrayPointer, myArrayPointerLength, np.NPY_FLOAT64)
m = MyClass()
print(m.myArray) # prints what it is supposed to print
m.myArray[0] = 1 # works
print(m.myArray) # prints what is expected, but terminates the program after freeing the freeing the pointer.
...