【问题标题】:Python - ctypes.c_char.from_buffer vs ctypes.c_void_p(string)Python - ctypes.c_char.from_buffer 与 ctypes.c_void_p(string)
【发布时间】:2018-11-08 19:17:56
【问题描述】:

两者有什么区别:

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_void_p('abc') 不起作用:^) 我看不出这段代码的意义。我认为create_string_buffer() 会和这个特定于操作系统的代码做同样的事情。
  • 哦,是的,它应该是 ctypes.c_char_p(string),在编辑中修复。但是您认为这些方式是否可以在其他平台上使用?例如。使用 ctypes.c_char_p(string) 并将其作为源参数传递给 ms api RtlMoveMemory 函数,我想知道这是否可行...
  • 感谢 btw @Mark,只是不能支持 b/c 没有足够的代表,但是是的 create_string_buffer() 也是创建 char 指针缓冲区的好方法,它只是一个 char 数组。跨度>

标签: python pointers ctypes kernel32 memmove


【解决方案1】:

经过多次测试,可以得出结论

第一:

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 

【讨论】:

    猜你喜欢
    • 2010-09-24
    • 2022-12-09
    • 2010-10-25
    • 1970-01-01
    • 2010-09-24
    • 2010-10-12
    • 2013-11-15
    • 2010-09-25
    • 1970-01-01
    相关资源
    最近更新 更多