[Tutor] ctypes wintypes

eryk sun eryksun at gmail.com
Fri Oct 6 16:55:24 EDT 2017

On Fri, Oct 6, 2017 at 9:12 PM, Michael C
<mysecretrobotfactory at gmail.com> wrote:
> How do I create a buffer, or rather, is a buffer just a variable?

A buffer is a block of memory for an I/O operation. For example, if
you need to read a 4-byte (32-bit) integer at an address in another
process, the 'buffer' could be ctypes.c_int32(). In general, to read
an arbitrary-sized block of memory, use ctypes.create_string_buffer()
to create a char array.

> How do I create a pointer to it?

Pass it byref().

> print('mbi.State: ',mbi.State)

Check whether mbi.State is MEM_COMMIT before trying to read it. If
it's MEM_FREE or MEM_RESERVE, then ReadProcessMemory will fail.

> buffer = ctypes.create_string_buffer(4)
> bufferSize = (ctypes.sizeof(buffer))
> ReadProcessMemory = Kernel32.ReadProcessMemory
> if ReadProcessMemory(Process, ctypes.byref(mbi), buffer, bufferSize, None):
>         print('buffer is: ',buffer)
> else:
>         print('something is wrong')

Don't print "something is wrong". You're capturing the thread's last
error value, so use it to raise an informative exception. For example:

    if not success:
        raise ctypes.WinError(ctypes.get_last_error())

More information about the Tutor mailing list