Python中用于Blob对象的ctypes和C++

0 投票
1 回答
678 浏览
提问于 2025-04-16 03:20

你好!

我想要一个可以在Python中传递的blob对象,偶尔把它交给一个C++函数来写入数据。

看起来ctypes是个不错的选择,但我在使用Python的标准函数时遇到了一些问题。

比如说:

>>> import ctypes
>>> T=ctypes.c_byte * 1000
>>> blob = T()
>>> ctypes.pointer(blob)
<__main__.LP_c_byte_Array_1000 object at 0x7f6558795200>

# Do stuff with blob data through the pointer in C++

>>> f = open('test.bin', 'wb')
>>> f.write(blob)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument 1 must be string or buffer, not _ctypes.ArrayType

我真的希望在不必要的情况下避免复制数据。

谢谢!

1 个回答

0

你可能会更好地使用字符串缓冲区,并通过 raw 属性的值来访问内容。

pstr = ctypes.create_string_buffer( 1000 )
f.write( pstr.raw )

撰写回答