我正在尝试使用 python ctypes 从共享库中使用这两个 C 函数:
bool decompress_rgb(unsigned char *data, long dataLen, int scale)
float* getRgbBuffer()
第一个函数运行良好。我可以通过将一些调试代码放入共享库并检查输入来判断。
问题是获取数据。 RGB 缓冲区是一个指向 float 的指针(很明显),并且该指针在应用程序的生命周期内保持不变。因此,每当我想解压缩图像时,我都会调用 decompress_rgb
,然后需要查看 getRgbBuffer
指向的位置有什么。我知道缓冲区大小是 (720 * 288 * sizeof(float)) 所以我想这必须在某个地方发挥作用。
没有 c_float_p
类型所以我想我会试试这个:
getRgbBuffer.restype = c_char_p
然后我做:
ptr = getRgbBuffer()
print "ptr is ", ptr
它只是输出:
ptr = 3078746120
我猜这是实际地址而不是内容,但即使我成功取消引用指针并获取内容,它也只是第一个字符。
如何将整个缓冲区的内容转换为 python 字符串?
编辑:必须更改:
getRgbBuffer.restype = c_char_p
到
getRgbBuffer.restype = c_void_p
但后来 BastardSaint 的回答奏效了。
最佳答案
没有经过全面测试,但我认为是这样的:
buffer_size = 720 * 288 * ctypes.sizeof(ctypes.c_float)
rgb_buffer = ctypes.create_string_buffer(buffer_size)
ctypes.memmove(rgb_buffer, getRgbBuffer(), buffer_size)
关键是 ctypes.memmove()
函数。来自ctypes documentation :
memmove(dst, src, count)
Same as the standard C memmove library function: copiescount
bytes fromsrc
todst
.dst
andsrc
must be integers or ctypes instances that can be converted to pointers.
运行上述代码段后,rgb_buffer.value
将返回第一个 '\0'
之前的内容。要将所有字节作为 Python 字符串获取,您可以对整个内容进行切片:buffer_contents = rgb_buffer[:]
。
关于python - 使用 python ctypes 将共享库中的 float 缓冲区转换为 python 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/704777/