1
votes

I've got a dll which defines a structure. Within this structure is a field that has the type CRITICAL_SECTION, as included from windows.h. How can I define a ctypes structure in python to reference this type? Since CRITICAL_SECTION is itself a struct (with references to other structs in its own definition), do I really have to define the python ctype equivalents such that I have a python CRITICAL_SECTION that I can reference? Is there a better way?

Example C program:

...
typedef struct some_struct {
    ...
    CRITICAL_SECTION field1;
} SOME_STRUCT;
...

Example Python program:

...
class SOME_STRUCT(Structure):
    _fields_ = [... ('field1', CRITICAL_SECTION)]

How do I make ctypes recognize what CRITICAL_SECTION is without going down the rabbit hole of defining everything down to primitive types that ctypes recognizes?

1
Untested, but for the purposes of Python, defining it as c_ubyte * x where x is sizeof(CRITICAL_SECTION) might be sufficient. As long as your final structure is the right size, you can just treat it as an opaque array of bytes. - Mark Tolonen
so what is the sizeof(CRITICAL_SECTION) anyway :D - Antti Haapala
@AnttiHaapala ask your C compiler :^) On mine it was 40 bytes, but it would vary. I came up with a hopefully better answer below. - Mark Tolonen

1 Answers

2
votes

You just have to get the top-level structure size right. InitializeCriticalSection should handle setting the structure up.

Looking into the Windows headers, this should work on 32- and 64-bit systems:

from ctypes import *
from ctypes import wintypes as w

# Set to an unsigned int type that is 32- or 64-bit depending on OS architecture.
# I didn't see a wintype that worked.
ULONG_PTR = c_size_t

class CRITICAL_SECTION(Structure):
    _fields_ = [('DebugInfo',w.LPVOID),
                ('LockCount',w.LONG),
                ('RecursionCount',w.LONG),
                ('OwningThread',w.HANDLE),
                ('LockSemaphore',w.HANDLE),
                ('SpinCount',ULONG_PTR)]

k32 = WinDLL('kernel32')
InitializeCriticalSection = k32.InitializeCriticalSection
InitializeCriticalSection.argtypes = POINTER(CRITICAL_SECTION),
InitializeCriticalSection.restype = None

s = CRITICAL_SECTION()
InitializeCriticalSection(byref(s))