flatbuffers icon indicating copy to clipboard operation
flatbuffers copied to clipboard

[Python] Invalid generated code for packing structs with array of struct fields

Open peter-soos opened this issue 1 month ago • 2 comments

using flatc version 25.2.10

namespace a;

struct Vec3 {
  v:[float:3];
}

struct Mat3 {
  r:[Vec3:3];
}
import flatbuffers

import a.Vec3
import a.Mat3

r0 = a.Vec3.Vec3T()
r1 = a.Vec3.Vec3T()
r2 = a.Vec3.Vec3T()

r0.v = [1.0, 2.0, 3.0]
r1.v = [4.0, 5.0, 6.0]
r2.v = [7.0, 8.0, 9.0]

builder = flatbuffers.Builder()

m = a.Mat3.Mat3T()
m.r = [r0, r1, r2]
m.Pack(builder)
`Traceback (most recent call last):
  File "/a/test.py", line 18, in <module>
    m.Pack(builder)
  File "/a/a/Mat3.py", line 89, in Pack
    return CreateMat3(builder, self.r.v)
AttributeError: 'list' object has no attribute 'v'`

Mat3.py Vec3.py

peter-soos avatar Nov 13 '25 16:11 peter-soos

I spent a few minutes poking around at this and think I understand what's going on.

The Pack function generator does a good job of drilling down through structs looking for the relevant fields to pass to Create* methods. However, it treats arrays of complex types as if they are single members of complex types, which is why we see the error.

For every member it discovers to pass to Create*, it needs to determine if that type is an array, and flatten that array into a local variable prior to calling Create*.

Here is the link to the function that generates the Pack function

jtdavis777 avatar Nov 14 '25 05:11 jtdavis777

I think some sort of wrapper View class which implements array index operators could also work, but may be more convoluted than it's worth.

jtdavis777 avatar Nov 14 '25 05:11 jtdavis777