[Tutor] ctypes wintypes

eryk sun eryksun at gmail.com
Thu Oct 5 14:34:18 EDT 2017


On Tue, Oct 3, 2017 at 10:30 PM, Michael C
<mysecretrobotfactory at gmail.com> wrote:
>
> I am trying to create SYSTEM_INFO structure  and MEMORY_BASIC_INFORMATION
> structure

First, avoid relying on constants, enumerations, and structures
published on MSDN. It's not always right. Get the SDK and use the
header files instead. MEMORY_BASIC_INFORMATION is defined in winnt.h,
and SYSTEM_INFO is defined in sysinfoapi.h.

MEMORY_BASIC_INFORMATION is simple. Don't worry about the
MEMORY_BASIC_INFORMATION32 and MEMORY_BASIC_INFORMATION64 versions.
Those are meant for a debugger that's reading this structure directly
from the memory of another process.

SYSTEM_INFO is a bit tricky, given the anonymous struct and union. I
prefer to nest the definitions, but you could flatten it as separate
definitions if you like. Refer to the docs for how to use _anonymous_:

https://docs.python.org/3/library/ctypes#ctypes.Structure._anonymous_

Here are the definitions. Please don't mindlessly copy and paste.
Recreate them on your own and use this example as a reference.

import ctypes
from ctypes.wintypes import WORD, DWORD, LPVOID

PVOID = LPVOID
SIZE_T = ctypes.c_size_t

# https://msdn.microsoft.com/en-us/library/aa383751#DWORD_PTR
if ctypes.sizeof(ctypes.c_void_p) == ctypes.sizeof(ctypes.c_ulonglong):
    DWORD_PTR = ctypes.c_ulonglong
elif ctypes.sizeof(ctypes.c_void_p) == ctypes.sizeof(ctypes.c_ulong):
    DWORD_PTR = ctypes.c_ulong

class MEMORY_BASIC_INFORMATION(ctypes.Structure):
    """https://msdn.microsoft.com/en-us/library/aa366775"""
    _fields_ = (('BaseAddress', PVOID),
                ('AllocationBase',    PVOID),
                ('AllocationProtect', DWORD),
                ('RegionSize', SIZE_T),
                ('State',   DWORD),
                ('Protect', DWORD),
                ('Type',    DWORD))

PMEMORY_BASIC_INFORMATION = ctypes.POINTER(MEMORY_BASIC_INFORMATION)

class SYSTEM_INFO(ctypes.Structure):
    """https://msdn.microsoft.com/en-us/library/ms724958"""
    class _U(ctypes.Union):
        class _S(ctypes.Structure):
            _fields_ = (('wProcessorArchitecture', WORD),
                        ('wReserved', WORD))
        _fields_ = (('dwOemId', DWORD), # obsolete
                    ('_s', _S))
        _anonymous_ = ('_s',)
    _fields_ = (('_u', _U),
                ('dwPageSize', DWORD),
                ('lpMinimumApplicationAddress', LPVOID),
                ('lpMaximumApplicationAddress', LPVOID),
                ('dwActiveProcessorMask',   DWORD_PTR),
                ('dwNumberOfProcessors',    DWORD),
                ('dwProcessorType',         DWORD),
                ('dwAllocationGranularity', DWORD),
                ('wProcessorLevel',    WORD),
                ('wProcessorRevision', WORD))
    _anonymous_ = ('_u',)

LPSYSTEM_INFO = ctypes.POINTER(SYSTEM_INFO)


More information about the Tutor mailing list