【问题标题】:Python ctypes.sizeof(...) always returns 0 [closed]Python ctypes.sizeof(...) 总是返回 0 [关闭]
【发布时间】:2018-07-27 22:02:30
【问题描述】:

根据我对 Python 的 ctypes 的了解,ctypes.sizeof(...) 应该返回传入结构的大小(以字节为单位),就像使用 C 的 sizeof 运算符一样。但是,结果我总是得到0

$ python
Python 2.7.12 (default, Dec  4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> class testStruct(ctypes.Structure):
...     _fields = [
...         ("testField", ctypes.c_uint*4)
...     ]
...
>>> ctypes.sizeof(testStruct)
0
>>> test = testStruct()
>>> ctypes.sizeof(test)
0

为什么会这样?

【问题讨论】:

    标签: python python-2.7 ctypes


    【解决方案1】:

    你忘了在_下划线_fields,应该是_fields_

    import ctypes
    class testStruct(ctypes.Structure):
        # NOT just _fields:
        _fields_ = [
            ("testField", ctypes.c_uint*4)
        ]
    
    print(ctypes.sizeof(testStruct))
    test = testStruct()
    print(ctypes.sizeof(test))
    

    输出:

    16
    16
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 2015-09-27
      • 2014-03-20
      • 2013-04-13
      • 2013-03-30
      相关资源
      最近更新 更多