python - Python - ctypes.c_char.from_buffer 与 ctypes.c_void_p(string)
问题描述
有什么区别:
pointer = ctypes.c_char_p('abc')
和
string = 'abc'
buffer = (ctypes.c_char * len(string)).from_buffer(string)
从技术上讲,它们在各自的函数调用中传递时都是指针,如下所示:(跨平台不同的函数调用)
if os.name == 'posix':
string = 'abc'
libc = ctypes.CDLL('libc.so.6')
# creating a pointer pointing at our string
s_ptr = ctypes.c_char_p(string)
# allocating free space
free_space_ptr = ctypes.c_void_p(libc.valloc(ctypes.c_int(len(string))))
# copying memory from one loc to another
ctypes.memmove(free_space_ptr, s_ptr, ctypes.c_int(len(string)))
else:
string = 'abc'
# allocating free space
free_space_ptr = ctypes.windll.kernel32.VirtualAlloc(...)
# creating a pointer pointing at our string?
buffer = (cytpes.c_char_p * len(string))).from_buffer(string)
# copying memory from one loc to another
ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_void_p(free_space_ptr), buffer, ctypes.c_int(len(shellcode)))
我的问题是:
两个函数调用(memmove 和 RtlMoveMemory)接受两个指针 ==> 目标、源,然后最后一个参数是要复制的长度。
获取指向我们字符串的指针的两种方式有什么区别?:
- 使用 ctypes.c_char_p(string)
对比
- 使用 ctypes.c_char.from_buffer(string)
解决方案
经过多次测试,可以得出结论
第一的:
ctypes.c_char.from_buffer(string)
不起作用,因为 from_buffer 方法接受一个字节数组的参数,所以我需要先将字符串转换为字节数组,如下所示:
buf = bytearray(string)
ptr = ctypes.c_char.from_buffer(string)
现在都返回了以下结果:
ctypes.c_char_p(string)
和
ctypes.c_char.from_buffer(buf)
可用于内存复制操作函数调用,如:
ctypes.memmove for linux
和
RtlMemoryMove for windows
推荐阅读
- python - Rpi 0 上的 Web Scraper 仅每 3-4 分钟抓取一次新数据?
- java - 意外的 ArrayList 大小
- sql - 具有重新启动增量的 Oracle SQL 行计数器
- android - Kotlin 代码从可变列表中删除一种特定类型的重复对象
- mysql - mysql 的不同结果匹配左连接表上的全文搜索
- anypoint-studio - 将 JSON 对象的元素作为数组返回
- javascript - Navber 不更新移动设备上的内容
- python - 如何为缺失值添加数据
- regex - 正则表达式提取“SELECT [whatever] FROM INSERTED”
- vue.js - HTML5 画布工件