Python ctypes:什么时候需要手动将 b`\0` 添加到 bytes 对象?
Python ctypes: when do you need to manually add b`\0` to a bytes object?
在 Python ctypes 中,当将 bytes
传递给期望 null 终止的函数时,何时需要手动添加 null/zero b'[=13=]'
终止符数据?
专门针对 3 个案例(但欢迎其他案例)
如果函数参数已通过其 argtypes
声明为 c_char_p
如果函数没有通过argtypes
声明其参数
使用memmove
,如果接口需要一个内存地址处的空终止字符串,
memmove(target, my_string.encode() + b'[=11=]', len(my_string.encode()) + 1)
或者你可以
memmove(target, my_string.encode(), len(my_string.encode()) + 1)
上下文:我在 sqlite-s3-query 中出于偏执狂添加 b'[=13=]'
,并尝试找出是否可以删除它们。如果我确实删除它们,它似乎工作正常,但我意识到在正确的位置可能恰好有空字节,所以一切正常。我正在寻找更有力的保证,即空字节是按设计存在的。
至少在 CPython 中,字节对象的内部缓冲区总是以 null 结尾的,不需要再添加一个。不管你是否指定.argtypes
,生成的指针都会指向这个缓冲区。
参考:https://docs.python.org/3/c-api/bytes.html#c.PyBytes_AsString:
char *PyBytes_AsString(PyObject *o)
Part of the Stable ABI.
Return a
pointer to the contents of o. The pointer refers to the internal
buffer of o, which consists of len(o) + 1
bytes. The last byte in the
buffer is always null, regardless of whether there are any other null
bytes....
在 Python ctypes 中,当将 bytes
传递给期望 null 终止的函数时,何时需要手动添加 null/zero b'[=13=]'
终止符数据?
专门针对 3 个案例(但欢迎其他案例)
如果函数参数已通过其 argtypes
声明为c_char_p
如果函数没有通过argtypes
声明其参数使用
memmove
,如果接口需要一个内存地址处的空终止字符串,memmove(target, my_string.encode() + b'[=11=]', len(my_string.encode()) + 1)
或者你可以
memmove(target, my_string.encode(), len(my_string.encode()) + 1)
上下文:我在 sqlite-s3-query 中出于偏执狂添加 b'[=13=]'
,并尝试找出是否可以删除它们。如果我确实删除它们,它似乎工作正常,但我意识到在正确的位置可能恰好有空字节,所以一切正常。我正在寻找更有力的保证,即空字节是按设计存在的。
至少在 CPython 中,字节对象的内部缓冲区总是以 null 结尾的,不需要再添加一个。不管你是否指定.argtypes
,生成的指针都会指向这个缓冲区。
参考:https://docs.python.org/3/c-api/bytes.html#c.PyBytes_AsString:
char *PyBytes_AsString(PyObject *o)
Part of the Stable ABI.
Return a pointer to the contents of o. The pointer refers to the internal buffer of o, which consists oflen(o) + 1
bytes. The last byte in the buffer is always null, regardless of whether there are any other null bytes....