Python ctypes - 如何处理字符串数组

标签 python ctypes

我正在尝试调用一个返回 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/

相关文章:

来自 C++ 的 Python 回调调用在 native 站点上失败

php - 在 Python 中,如何从动态加载的网站请求特定数据?

python - 排序 OrderedDict 不起作用

python - libeay32.dll 的包装器 : how to import macro?

python - Ctypes wstring 通过引用传递

python - 将 array.array 的内容放入堆中

python - 传递大型数组时 OSX 10.10 上的 ctypes 段错误 11

python - 尝试制作一种检查字符串的算法,然后输出最长的子字符串

python - 文档字符串应该放在装饰器之前还是之后?

python - PyPi 上缺失模块的总下载量