3

I have the following definitions in my schema file:

union UGeometry { Polygon, Point, Linestring }

table Point {
    point:Vec2;
}

table Polygon {
    points:[Vec2List]; 
}

table Geometry {
    g:UGeometry;
}

(Removed some boilerplate code for type checking and other things)

The table Geometry stores geometries of type Point, Polygon and LineString. I can access this in C++ and Javascript as usual, e.g. in Javascript I use the following to get a Polygon type:

var rawPolygon = flatBufGeometry.g( new storage.Polygon() );

However, I cannot find such accessor in the generated Python code. The following won't work:

rawPolygon = rawGeometry.G()(storage.Polygon.Polygon())

How can I access Flatbuffers union objects in a table using Python?

benjist
  • 2,740
  • 3
  • 31
  • 58

1 Answers1

3

Here's an example of Google's monster.fbs as all flatbuffer have a similar structure and generated python file.

union Equipment { Weapon } // Optionally add more tables.


table Monster {
  pos:Vec3;
  mana:short = 150;
  hp:short = 100;
  name:string;
  friendly:bool = false (deprecated);
  inventory:[ubyte];
  color:Color = Blue;
  weapons:[Weapon];
  equipped:Equipment;
  path:[Vec3];
}

table Weapon {
  name:string;
  damage:short;
}

root_type Monster;

to Access Weapon, try

import MyGame.Sample.Equipment
import MyGame.Sample.Weapon

union_weapon = MyGame.Sample.Weapon.Weapon()
union_weapon.Init(monster.Equipped().Bytes, monster.Equipped().Pos)

source: https://github.com/google/flatbuffers/blob/master/samples/monster.fbs https://github.com/google/flatbuffers/blob/master/samples/sample_binary.py

Qihang Xu
  • 31
  • 2