定义具有未知字段类型的python ctypes结构

时间:2017-09-28 19:31:17

标签: python c ctypes

我有一个定义结构的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识别的原始类型?

1 个答案:

答案 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))