linux - 如何为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, value, 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
)。
推荐阅读
- pandas - 按其他数据框排序数据框
- c# - 在 Visual Studio 2019 中更改 C# 版本
- reactjs - 无法使用 react-image-crop 裁剪图像
- java - 如何在不简单地在 Java 中使用 for 循环的情况下执行 n 个数组的元素相加
- mysql - mysql 工作台表编辑器数据更新的怪癖?
- javascript - 如果文本超过 2 个字符,则获取上一页数
- visual-studio-code - 更改 VS Code 中的默认 Emmet 设置
- vba - 如何通过列表框中的项目更改表中的新列
- python - 使用 Python 从 html 网站获取链接的名称
- apache-kafka - 错误:无法找到或加载主类文件\kafka_2.12-2.4.0\libs\activation-1.1.1.jar;