我需要就地修改Pythonstr
。如何在不首先转换为bytes
的情况下使用ctypes.memmove
执行此操作?我的目标是节省内存,转换为bytes
将生成字符串的副本,这使得首先使用ctypes毫无意义。
我尝试转换为c_wchar_p
,但这对newstr
实例没有任何作用
dest = POINTER(c_char)(c_char.from_address(addressof(ctypes.c_wchar_p(newstr))))
source = POINTER(c_char)(c_char.from_address(addressof(ctypes.c_wchar_p(newstr)) + 1))
ctypes.memmove(
dest,
source,
length - 1,
)
我怎样才能做到这一点?
>>> import ctypes
>>> import sys
>>> s = "Hello World"
>>> s_mem = (ctypes.c_byte * len(s)).from_address(id(s) + sys.getsizeof(s) - len(s) - 1)
>>> ctypes.memmove(s_mem, b"Howdy", 5)
139669939550304
>>> s
'Howdy World'
参考文献:
- PEP 393
- GitHub:python/cpython/Include/cpython/unicodeobject.h