Python - ctypes.c_char.from_buffer 与 ctypes.c_void_p(字符串)

Python - ctypes.c_char.from_buffer vs 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)接受两个指针 ==> destination,source,最后一个参数是要复制的长度。

获取指向我们字符串的指针的两种方式有什么区别?:

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

第一个:

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