Python - ctypes.c_char.from_buffer vs ctypes.c_void_p(string)

时间:2018-05-30 03:53:17

标签: python pointers ctypes kernel32 memmove

之间有什么区别:

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)

VS

  • 使用ctypes.c_char.from_buffer(string)

1 个答案:

答案 0 :(得分:0)

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

第一:

ctypes.c_char.from_buffer(string)

不会工作,因为from_buffer方法接受一个字节数组的param,所以我需要先将字符串转换为字节数组,如下所示:

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