使用python ctypes将浮动缓冲区从共享库获取到python字符串

2024-07-08 10:59:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用python ctypes从共享库中使用这两个C函数:

bool decompress_rgb(unsigned char *data, long dataLen, int scale)
float* getRgbBuffer()

第一个功能运行良好。我可以通过在共享库中放入一些调试代码并检查输入来判断。

问题是把数据拿出来。RGB缓冲区是一个指向浮点(显然)的指针,该指针在应用程序的生命周期中保持不变。因此,每当我想解压缩一个图像时,我都会调用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

但巴斯塔圣的回答奏效了。


Tags: 函数内容rgbfloatctypesdecompress缓冲区指向
2条回答

我已经有一段时间没有使用ctypes了,我也没有足够方便的返回“double*”的东西来测试它,但是如果你想要一个c_float_p:

c_float_p = ctypes.POINTER(ctypes.c_float)

读了巴斯塔德圣的答案,你只需要原始数据,但我不确定你这样做是否是为了解决没有cúu floatúp的问题

还没有完全测试,但我认为是沿着这条路线:

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[:]

相关问题 更多 >

    热门问题