Skip to content

Commit

Permalink
Reland corrected "Prevent setting nonexistent struct fields"
Browse files Browse the repository at this point in the history
  • Loading branch information
mara004 committed Nov 12, 2023
1 parent cca2773 commit 5148408
Showing 1 changed file with 12 additions and 14 deletions.
26 changes: 12 additions & 14 deletions ctypesgen/printer_python/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,12 @@ def print_typedef(self, typedef):
def print_struct(self, struct):
self.srcinfo(struct.src)
base = {"union": "Union", "struct": "Structure"}[struct.variety]
self.file.write("class %s_%s(%s):\n" " pass" % (struct.variety, struct.tag, base))

def print_struct_members(self, struct):

self.file.write(f"class {struct.variety}_{struct.tag} ({base}):\n")
tab = " "*4

if struct.opaque:
self.file.write(tab + "pass")
return

# is this supposed to be packed?
Expand All @@ -259,7 +261,7 @@ def print_struct_members(self, struct):
if isinstance(aligned, ExpressionNode):
# TODO: for non-constant expression nodes, this will fail:
aligned = aligned.evaluate(None)
self.file.write("{}_{}._pack_ = {}\n".format(struct.variety, struct.tag, aligned))
self.file.write(tab + f"_pack_ = {aligned}\n")

# handle unnamed fields.
unnamed_fields = []
Expand All @@ -279,18 +281,14 @@ def print_struct_members(self, struct):
if type(mem[1]) is CtypesStruct:
unnamed_fields.append(name)
struct.members[mi] = mem

self.file.write("%s_%s.__slots__ = [\n" % (struct.variety, struct.tag))
for name, ctype in struct.members:
self.file.write(" '%s',\n" % name)
self.file.write("]\n")


if len(unnamed_fields) > 0:
self.file.write("%s_%s._anonymous_ = [\n" % (struct.variety, struct.tag))
for name in unnamed_fields:
self.file.write(" '%s',\n" % name)
self.file.write("]\n")
self.file.write(tab + f"_anonymous_ = {unnamed_fields}\n")

self.file.write(tab + f"__slots__ = {[n for n, _ in struct.members]}\n")

def print_struct_members(self, struct):
# Fields must be defined indepedent of the actual class to handle self-references, cyclic struct references and forward declarations
self.file.write("%s_%s._fields_ = [\n" % (struct.variety, struct.tag))
for name, ctype in struct.members:
if isinstance(ctype, CtypesBitfield):
Expand Down

0 comments on commit 5148408

Please sign in to comment.