Issue
I have created subtructure and structure in ctypes as below where I am defining a array of substructure inside structure with some predefined size. (As per requirement SIZE
may be set to 0
initially and can varies based on user input).
from ctypes import *
class MySubStructure(Structure):
_fields_ = [
("sub_field1", c_uint32),
("sub_field2", c_uint32)
]
class MyStructure(Structure):
SIZE = 2
_fields_ = [
("field1", c_uint32),
("field2", c_uint32),
("sub_structure_field", ARRAY(SubStructure, SIZE)),
]
My goal is to modify this substructure based on user input.
For achieving the same I have tried below options but had no success:
Defining a
__init__
method and updating_fields_
while initializing the instanceUpdating
_fields_
after initializing instance
For both of those options I tried to appending sub_structure_field
, updating only size value by accessing through index.
Finally I just want a workaround so that I can use array of structure inside another structure either initializing at runtime or modifying at runtime.
Solution
Mentioning [Python 3.Docs]: ctypes - A foreign function library for Python.
The array size must be known at the moment _fields_ is defined.
You could have a factory function which defines the class and returns it.
script0.py:
#!/usr/bin/env python3
import sys
import ctypes
class SubStructure(ctypes.Structure):
_fields_ = [
("sub_field1", ctypes.c_uint32),
("sub_field2", ctypes.c_uint32),
]
def structure_factory(size):
class DynamicStructure(ctypes.Structure):
_fields_ = [
("field1", ctypes.c_uint32),
("field2", ctypes.c_uint32),
("sub_structure_field", ctypes.ARRAY(SubStructure, size)), # 2nd element equivalent to SubStructure * size
]
return DynamicStructure
def main():
Struct2 = structure_factory(2)
Struct5 = structure_factory(5)
print(Struct2.sub_structure_field)
print(Struct5.sub_structure_field)
if __name__ == "__main__":
print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
main()
print("\nDone.")
Output:
[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q057417435]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" script0.py Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] 64bit on win32 <Field type=SubStructure_Array_2, ofs=8, size=16> <Field type=SubStructure_Array_5, ofs=8, size=40> Done.
You could also take a look at [SO]: Setting _fields_ dynamically in ctypes.Structure (@CristiFati's answer).
Answered By - CristiFati
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.