我正在尝试调用一个返回 a NULL-terminated array of NULL-terminated strings 的外部库函数.
kernel32 = ctypes.windll.kernel32
buf = ctypes.create_unicode_buffer(1024)
length = ctypes.c_int32()
if kernel32.GetVolumePathNamesForVolumeNameW(ctypes.c_wchar_p(volume),
buf, ctypes.sizeof(buf), ctypes.pointer(length)):
## ???
换句话说:
buf = ctypes.create_unicode_buffer(u'Hello\0StackOverflow\0World!\0')
如何访问 所有 buf
的内容作为 Python 列表? buf.value
只达到到第一个 NULL。
在 C 中它会是这样的:
while (*sz) {;
doStuff(sz);
sz += lstrlen(sz) + 1;
}
最佳答案
在发现 ctypes.wstring_at()
和 ctypes.addressof()
之后,我得到了这个:
def wszarray_to_list(array):
offset = 0
while offset < ctypes.sizeof(array):
sz = ctypes.wstring_at(ctypes.addressof(array) + offset*2)
if sz:
yield sz
offset += len(sz)+1
else:
break
关于Python ctypes - 如何处理字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3073478/