google/flatbuffers

native_type for tables in c++ object based api

Open

#4969 opened on Oct 4, 2018

View on GitHub
 (22 comments) (1 reaction) (0 assignees)C++ (25,952 stars) (3,564 forks)batch import
help wantednot-stalepr-requested

Description

Hi everybody, I like to use custom types for tables in the object based API. The behavior should be equal to the "native_type" attribute for structs. I hope to get some feedback on the idea and possible pack and unpack APIs.

Example:

table MatrixXd (native_type:"Eigen::MatrixXd") {
  rows:uint32;
  data:[double];
}

table Signal {
  mat:MatrixXd;
}

I like to get an object API similar to:

struct SignalT {
  Eigen::MatrixXd mat; // instead of std::unique_ptr<MatrixXdT>mat;
}

For structs the user has to specify the following functions:

namespace flatbuffers { 
native_type UnPack(const FlatbufferStruct& obj); 
FlatbufferStruct Pack(const native_type& obj); 
}

I think this is no suitable interface for tables, as "Pack" should directly map to a FlatBufferBuilder.

UnPack default is { auto _e = mat(); if (_e) _o->mat = std::unique_ptr<MatrixXdT>(_e->UnPack(_resolver)); }; The actual unpack functionality is implemented in "UnPackTo". Both UnPack and UnPackTo are members of the generated code and thus can not be user defined. I would suggest:

native_type UnPack(const FlatbufferTable& obj, const flatbuffers::resolver_function_t *_resolver = nullptr); or alternatively
void UnPackTo(native_type *_o, const FlatbufferTable& obj, const flatbuffers::resolver_function_t *_resolver = nullptr); I would prefer the first version. Return value optimization should do it's job.

Pack There is a "Pack" method generated for each Table. On the other hand there are two overloaded CreateType functions which do the actual work. I think the interface is similar to what we like to have.

Suggestion: inline flatbuffers::Offset<Signal> CreateSignal(flatbuffers::FlatBufferBuilder &_fbb, const native_type &_o, const flatbuffers::rehasher_function_t *_rehasher);

I think it is possible to clean up the various generated code pack and unpack functions. For compatibility reasons we should not do so? I am looking forward to some feedback.

Best regards Thomas

Contributor guide