【发布时间】: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 结构数组的最佳方式。
【问题讨论】:
-
请查看[SO]: How to create a Minimal, Complete, and Verifiable example (mcve)。添加代码的所有缺失部分,因为错误可能在其中。另外,Python 版本,OS 也会很有用。
-
“其中 _call() 是检查返回值的包装器。” - 请注意,您不需要使用它 - ctypes 允许您指定
_check_retval_ -
或通过
.errcheck
标签: python numpy ctypes structured-array