我有一个定义结构的dll。在此结构中,字段的类型为CRITICAL_SECTION
,包含在windows.h
中。如何在python中定义ctypes结构来引用这种类型?由于CRITICAL_SECTION
本身就是一个结构(在其自己的定义中引用了其他结构),我真的必须定义python ctype等价物,这样我才能引用python CRITICAL_SECTION
吗?还有更好的方法吗?
示例C程序:
...
typedef struct some_struct {
...
CRITICAL_SECTION field1;
} SOME_STRUCT;
...
示例Python程序:
...
class SOME_STRUCT(Structure):
_fields_ = [... ('field1', CRITICAL_SECTION)]
如何让ctypes识别CRITICAL_SECTION
是什么,而不是将所有内容定义为ctypes识别的原始类型?
答案 0 :(得分:2)
您必须正确地获得顶级结构大小。 InitializeCriticalSection
应该处理设置结构。
查看Windows标头,这应该适用于32位和64位系统:
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))