【问题标题】:Array of structs to NumPy structured array: np.ctypeslib.as_array from ndpointer结构数组到 NumPy 结构化数组:来自 ndpointer 的 np.ctypeslib.as_array
【发布时间】:2018-12-24 07:42:30
【问题描述】:

我正在尝试调用一个 C 函数,该函数接受指向指针的指针并将其重定向到内部分配的一维数组,沿着这条线:

typedef myStruct {
    const char* name;
    int status;
} myStruct;

int foo(const myStruct** array, size_t* size);

我正在尝试用 Python 和 NumPy 包装它,并获得一个包装该内部存储器的 NumPy 数组(作为只读)。

我有以下内容:

arr = np.ctypeslib.ndpointer(dtype=np.dtype([('name', np.intp),
                                             ('status', np.int)]))()
size = ct.c_size_t()
_call('foo', ct.byref(arr), ct.byref(size))
arr = np.ctypeslib.as_array(arr, shape=(size.value,))
arr.flags.writeable = False # not our memory!

_call() 是一个检查返回值的包装器。

我得到以下信息:

ValueError: '<P' is not a valid PEP 3118 buffer format string

致电as_array()。我做错了什么?


编辑:我的目标是将数据读取为 NumPy 结构化数组,因为我认为这是在 python 中描述 C 结构数组的最佳方式。

【问题讨论】:

标签: python numpy ctypes structured-array


【解决方案1】:

这可能被视为ndpointer 中的错误 - 问题是as_array 检查其参数是否为指针,但该测试对于 ndpointer 失败,并且 numpy 尝试创建一个包含单个指针(因为 numpy 没有指针类型而失败)。

完全不用 numpy 也能过得很好:

class myStruct(ctypes.Structure):
    _fields_ = [
        ('name', ctypes.c_char_p),
        ('status', ctypes.c_int),
    ]

arr = ctypes.POINTER(myStruct)()
size = ct.c_size_t()
_call('foo', ct.byref(arr), ct.byref(size))

# convert from `myStruct*` to `myStruct[size]`
arr = ctypes.cast(arr, ctypes.POINTER(myStruct * size.value)).contents

arr 现在是一个 ctypes 数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-08
    • 2013-03-12
    • 2018-08-09
    • 2016-10-10
    • 2016-03-29
    • 2012-08-12
    • 2016-04-28
    • 1970-01-01
    相关资源
    最近更新 更多