C函数(以下代码中的image_data
变量)返回指向类型为POINTER(c_ubyte)
的缓冲区的指针。我希望这些数据由Python管理,因此我想将它复制到bytearray
。这里的函数调用Python`ctypes` - 如何将C函数返回的缓冲区复制到字节数组中
image_data = stb_image.stbi_load(filename_cstr, byref(width),
byref(height), byref(num_channels),
c_int(expected_num_channels))
我们得到了只有电话后知道图像的width
和height
,所以不能预先分配bytearray
。
我会用
array_type = c.c_ubyte * (num_channels.value * width.value * height.value)
image_data_bytearray = bytearray(cast(image_data, array_type))
但类型cast
到必须是一个指针,而不是数组,所以我得到一个错误。
TypeError: cast() argument 2 must be a pointer type, not c_ubyte_Array_262144
我该怎么办?
你会发现这个有用:https://stackoverflow.com/questions/4355524/getting-data-from-ctypes-array-into-numpy - NumPy的是一个很好的图书馆数据处理的类型。 –
您可以有一个指向数组的指针,例如'ptype = POINTER(c_ubyte *(num_channels.value * width.value * height.value))'。通过使用'from_buffer'复制源指针的地址来获取实例,然后解引用以获取可传递给'bytearray'的数组,例如'image_data_bytearray = bytearray(ptype.from_buffer(image_data)[0])''。 – eryksun