python - 使用 python ctypes 将共享库中的 float 缓冲区转换为 python 字符串

标签 python pointers return-value ctypes

我正在尝试使用 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: copies count bytes from src to dst. dst and src 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/

相关文章:

c++ - 错误 : request for member (maybe you meant to use '->' ? ) 已经使用 '->'

c - 为什么这个指针出现段错误 C?

Pascal 中作为返回值的函数

python - 从 Python 函数返回多个值

python - f.write 与打印 >> f

c++ - int 指针数组

python - 递归点字典

c - "if"函数在 C 中出现 "control may reach end of non-void function"错误

python - pandas 结合两个字符串忽略 nan 值

python - 如何解决无法导入名称页面(django/wagtail)