首页 文章

如何使用Python访问属于对象的动态C数组变量?

提问于
浏览
1

我有一个带有变量的C类,它是一个动态数组 . 它非常简单,目前仅用于测试目的:

class testClass {

public:
    int *x;

    testClass();
    ~testClass();
};

变量 x 初始化为一些值,目前通过构造函数 . 我试图通过Cython为C类编写一个python包装器代码,可以访问 x . 我怎样才能做到这一点?

最好的办法是能够在不复制大量数据的情况下访问变量,因为 x 可能很大 . 我可以访问它 as a numpy 数组吗?

例如,它表现为 numpy 数组,可以只读取例如?我希望能够在使用python的其他计算中使用 x 中的数据,因此首选 numpy 数组 .

我想我可以创建一个初始化 numpy 数组的 GET 方法,将它传递给 GET 方法并用循环中的 x 数据填充它,但这会复制数据,看起来并不优雅 . 希望有更好的解决方案 .

我尝试过使用静态数组,并找到了一种有效的解决方案 . 如果 x 是静态的,我可以在 .pyx 文件中执行以下操作:

cdef extern from "testClass.h":
    cdef cppclass testClass:
        testClass()
        int x[5]

cdef class pyTestClass:
    cdef testClass *thisptr

    def __cinit__(self):
        self.thisptr = new testClass()
    def __dealloc__(self):
        del self.thisptr

    property x:
        def __get__(self):
            return self.thisptr.x

如果我在Python中访问 x ,我将获得一个包含值的Python列表 .


如何使用Python访问属于对象的动态C数组变量?

1 回答

  • 0

    看一下this example,它解释了如何在没有数据副本的情况下将C中分配的数组暴露给numpy . 例如,在Cython中创建已分配数据的1D numpy整数数组的相关行是,

    ndarray = np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT, data_pointer)
    

    请参阅相应的Numpy documentation .

相关问题