如何解决如何为python中的malloc创建的空间分配值?
我试图为python(Ubuntu 18.04 linux)中的malloc创建的空间分配一个值(字节),但是不知道如何...
dllc = CDLL("lib.so.6")
malloc = dll.malloc
malloc.restype = c_void_p
malloc.argtypes = (c_size_t,)
#initialize a pointer using malloc and allocate a space of size 1032
ptr = malloc(1032)
#here is the sample value of size 1032 in bytes
value = b'xxxxxxxxxxxxxxxxx......xxxxxxxx'
我实际上尝试使用memcpy复制值,但是结果值与原始值不一样...
memcpy = dllc.memcpy
memcpy.restype = c_void_p
memcpy.argtype = (c_void_p,c_void_p,c_size_t)
#copy value to the space referenced by ptr
memcpy(ptr,id(value),1032)
取消引用指针后,该值与分配的值不同
import ctypes
#dereference the pointer but the value doesn't match
ctypes.cast(ptr,ctypes.py_object).value
有人可以帮忙吗...
解决方法
您不应该使用id
,因为您可以将字节缓冲区传递给memcpy
。
我在Windows上,因此仅第一行有所不同,但其余代码应能工作:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ctypes
def main():
dll = ctypes.CDLL("msvcrt")
malloc = dll.malloc
malloc.restype = ctypes.c_void_p
malloc.argtypes = (ctypes.c_size_t,)
memcpy = dll.memcpy
memcpy.restype = ctypes.c_void_p
memcpy.argtypes = (ctypes.c_void_p,ctypes.c_void_p,ctypes.c_size_t)
alloc_size = 1032
ptr = malloc(alloc_size)
value = b"A" + b"X" * 1030 + b"B"
assert len(value) == alloc_size
# note that ctypes has a memmove method.
# ctypes.memmove(ptr,value,alloc_size)
memcpy(ptr,alloc_size)
# cast the pointer to a char*
pchar = ctypes.cast(ptr,ctypes.c_char_p)
# print the first,some of the in-between and the last bytes.
print(pchar.value[0],pchar.value[1:10],pchar.value[alloc_size - 1])
if __name__ == "__main__":
main()
输出:
65 b'XXXXXXXXX' 66
还要注意,ctypes有一个memmove
(因此您不需要memcpy
)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。