Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ctypes.sizeof(...) always returns 0 [closed]

From what I understand about Python's ctypes, ctypes.sizeof(...) should return the size, in bytes, of the structure passed in, as if using C's sizeof operator. However, I always get 0 as a result:

$ 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

Why is this happening?

like image 323
Jashaszun Avatar asked Feb 17 '26 19:02

Jashaszun


1 Answers

You forgot to put underscore _ to _fields, it should be _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))

Output:

16
16
like image 89
Andrej Kesely Avatar answered Feb 20 '26 09:02

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!