gpt4 book ai didi

ctypes - 将 ctypes.c_void_p() 和 ctypes.c_size_t() 转换为字节数组或字符串?

转载 作者:行者123 更新时间:2023-12-03 08:20:11 29 4
gpt4 key购买 nike

我似乎找不到任何将 ctypes.c_void_p() 转换为字符串或字节数组的简单示例。有没有简单的衬里可以做到这一点?

最佳答案

给你:

import ctypes as ct

# set up some void pointers to valid string and byte array
data = b'some string\0with null in it'
data1 = ct.c_char_p(data)
size1 = ct.c_size_t(len(data))
data2 = (ct.c_ubyte * 8)(1, 2, 3, 4, 5, 6, 7, 8)
size2 = ct.c_size_t(8)
void1 = ct.cast(data1, ct.c_void_p) # void* to nul-terminated string
void2 = ct.cast(data2, ct.c_void_p) # void* to eight bytes of data
print(void1, size1)
print(void2, size2)

# cast void* to the data being pointed to, and retrieve its contents
s = ct.cast(void1, ct.POINTER(ct.c_char * size1.value)).contents
print(s)
print(s.value) # up to nul-termination
print(s.raw) # full array

# cast void* to the data being pointed to, and retrieve its contents
b = ct.cast(void2, ct.POINTER(ct.c_ubyte * size2.value)).contents
print(b)
print(b[2])
print(list(b))

输出:

c_void_p(1678408544912) c_ulonglong(27)
c_void_p(1678408467720) c_ulonglong(8)
<__main__.c_char_Array_27 object at 0x00000186C8F0CBC0>
b'some string'
b'some string\x00with null in it'
<__main__.c_ubyte_Array_8 object at 0x00000186C8F0C840>
3
[1, 2, 3, 4, 5, 6, 7, 8]

关于ctypes - 将 ctypes.c_void_p() 和 ctypes.c_size_t() 转换为字节数组或字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68075730/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com