You need to enable JavaScript to run this app. 如何在Python中调用GetLogicalProcessorInformation()并定义结构体?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中调用GetLogicalProcessorInformation()并定义结构体?

对应结构的ctypes实现

核心类型映射说明

  • ctypes中实现C语言联合体,直接继承Union类即可,内存布局和原生C联合体完全一致,所有成员共享同一块起始内存
  • 原生LPVOID类型直接用c_void_p承载即可,对应空指针场景直接传None就能匹配原生NULL值
  • 注意使用与系统位宽匹配的类型:原生ULONG_PTR需要用c_size_t定义,不能用固定大小的整数类型,否则64位系统下会出现内存错位

完整可运行代码

from ctypes import (
    Structure, Union, c_ubyte, c_uint16, c_uint32, 
    c_uint64, c_size_t, sizeof, byref, windll
)

# 常用枚举值定义
RelationProcessorCore = 0
RelationNumaNode = 1
RelationCache = 2
RelationProcessorPackage = 3
RelationGroup = 4

# 联合体内部嵌套子结构定义
class ProcessorCoreInfo(Structure):
    _fields_ = [
        ("Flags", c_ubyte)
    ]

class NumaNodeInfo(Structure):
    _fields_ = [
        ("NodeNumber", c_uint32)
    ]

class CacheDescriptor(Structure):
    _fields_ = [
        ("Level", c_ubyte),
        ("Associativity", c_ubyte),
        ("LineSize", c_uint16),
        ("Size", c_uint32),
        ("Type", c_uint32)
    ]

class CacheInfo(Structure):
    _fields_ = [
        ("Cache", CacheDescriptor)
    ]

# 对应API要求的联合体结构
class SystemLogicalProcessorUnion(Union):
    _fields_ = [
        ("ProcessorCore", ProcessorCoreInfo),
        ("NumaNode", NumaNodeInfo),
        ("Cache", CacheInfo),
        ("Reserved", c_uint64 * 2)  # 对齐预留,保证结构尺寸完全匹配原生定义
    ]

# 最外层对应API返回的核心结构
class SystemLogicalProcessorInfo(Structure):
    _fields_ = [
        ("ProcessorMask", c_size_t),  # 对应原生ULONG_PTR,随系统位宽自动适配
        ("Relationship", c_uint32),
        ("Union", SystemLogicalProcessorUnion)
    ]

def get_logical_processor_info():
    # 第一次调用:获取需要的缓冲区大小
    return_len = c_uint32(0)
    windll.kernel32.GetLogicalProcessorInformation(None, byref(return_len))
    
    struct_size = sizeof(SystemLogicalProcessorInfo)
    entry_count = return_len.value // struct_size

    # 分配结构数组并填充数据
    info_array = (SystemLogicalProcessorInfo * entry_count)()
    success = windll.kernel32.GetLogicalProcessorInformation(byref(info_array), byref(return_len))
    if not success:
        raise OSError("调用系统接口失败")

    # 解析返回结果
    parsed_result = []
    for entry in info_array:
        item = {
            "processor_mask": entry.ProcessorMask,
            "relationship": entry.Relationship
        }
        # 根据关系类型读取联合体对应字段
        if entry.Relationship == RelationProcessorCore:
            item["flags"] = entry.Union.ProcessorCore.Flags
        elif entry.Relationship == RelationNumaNode:
            item["node_number"] = entry.Union.NumaNode.NodeNumber
        elif entry.Relationship == RelationCache:
            item["cache_detail"] = {
                "level": entry.Union.Cache.Cache.Level,
                "associativity": entry.Union.Cache.Cache.Associativity,
                "line_size": entry.Union.Cache.Cache.LineSize,
                "size": entry.Union.Cache.Cache.Size,
                "type": entry.Union.Cache.Cache.Type
            }
        parsed_result.append(item)
    return parsed_result

补充说明

  • 结构体的对齐规则完全由ctypes按照当前系统的默认编译规则处理,不需要手动计算偏移量
  • 你之前实现的GlobalMemoryStatusEx逻辑存在两处小问题:一是length字段原生为DWORD类型,对应ctypes的c_uint32而非c_int32;二是类初始化逻辑写在了类外部,需要移到类的__init__方法内部才能正常实例化
  • 联合体里的Reserved预留数组不能省略,否则会导致整体结构体尺寸和原生定义不匹配,引发内存读取错位

内容的提问来源于stack exchange,提问作者LTWood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.05 10:27:05