Skip to content

Support partial anonymous nested structs and unions - #295

Open
M-Colley wants to merge 1 commit into
python-cffi:mainfrom
M-Colley:fix/issue-36-nested-partial-structs
Open

M-Colley wants to merge 1 commit into
python-cffi:mainfrom
M-Colley:fix/issue-36-nested-partial-structs

Conversation

@M-Colley

Copy link
Copy Markdown

Declaring a partial anonymous nested struct or union field in ffi.cdef() previously raised NotImplementedError. Specifically, src/cffi/cparser.py omitted the nested flag for named struct, union, and array field declarations, and src/cffi/recompiler.py lacked an enclosing C type path to emit sizeof and offsetof expressions for unnamed partial structs. Fixes #36.

This patch records the enclosing parent type and field designator on StructOrUnion in src/cffi/model.py and propagates nested field context through src/cffi/cparser.py. Consequently, src/cffi/recompiler.py resolves the named ancestor type path and emits standard C sizeof, relative offsetof, and _cffi_array_len expressions for partial anonymous nested structs, unions, and struct arrays. Additionally, testing/cffi1/test_recompiler_codegen.py adds regression tests covering nested partial structs, arrays, unions, unnamed wrappers, and pointer rejection.

Verification ran pytest on testing/cffi1/test_recompiler_codegen.py and testing/cffi0/test_model.py, passing all 18 tests.

Fixes python-cffi#36.

Signed-off-by: Mark Colley <39366189+M-Colley@users.noreply.github.com>
@mattip

mattip commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

I think this can be simplified:

  • cparser.py: the nested flag is now redundant, since it's always the same as nested_in is not None. You can drop it and have _make_partial check tp.enclosing is None instead.
  • recompiler.py: replace _struct_access_path and the separate root_cname/access_path branches with one helper that returns a pointer expression for the struct. For a nested struct that's (&((struct a*)0)->d); for a named one it's ((struct a *)0). Field sizes, struct size and _cffi_array_len then use that one expression. Two extra error branches go away because get_c_name() already raises the same error. The check in _add_missing_struct_unions becomes tp.enclosing is None.

What do you think?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CFFI 1.16.0 fails to recognize nested structs properly for purposes of partial notation

2 participants