flatbuffers 使用问题记录

1.  命名空间的问题
-----------------------------

namespace 1.0.3 版本包含文件类型前面不需要加命名空间,但是1.1.0 中包含需要在类型前加命名空间

include必须放在namespace前面
例如:
include “aa.fbs”
namespace IM.test;



foo.fbc
namespace foo;
struct Foo { f: uint; }

bar.fbc
include "foo.fbc";
namespace bar;
struct Bar { foo: Foo; }

flatc -c bar.fbc will fail with bar.fbc:3:0: error: structs_ may contain only scalar or struct fields

修改方式:
struct Bar { foo: Foo; } ->  struct Bar { foo: foo.Foo; }  或者 将 struct 修改成 table



struct UserInfo{
        user_id:uint;
                    name:string
}

error: structs_ may contain only scalar or struct fields

因为 struct 结构中不能使用 string 类型,修改成  table 即可

2. struct 和 table的区别 ------------------------------ http://www.coder4.com/archives/4386 基本类型: 8 bit: byte ubyte bool 16 bit: short ushort 32 bit: int uint float 64 bit: long ulong double 复杂类型: 数组 (用中括号表示 [type]). 不支持嵌套数组,可以用table实现 字符串 string, 支持 UTF-8 或者 7-bit ASCII. 对于其他编码可以用数组 [byte]或者[ubyte]表示。 Struct 只支持基本类型或者嵌套Struct Table 类似Struct,但是可以支持任何类型。 3. roottype的问题及多个table的解决方式 ------------------------------------------ https://github.com/google/flatbuffers/issues/65 Why the need for a Root 1) a commit was pushed yesterday that adds GetRootAs functions for all tables, not just the root_type. 2) generally no. this is a strongly types system, meaning you need to know the kind of buffer you're dealing with. If you want to use this in a context where you want to have multiple different root types, you have these options: a) make your root type a table that contains a union of all possible sub-roots. b) prefix flatbuffers with your own file header c) use flatbuffer's built-in file indentification feature, which hasn't been ported to Java yet. I'll get to that. 3) That's a bug, the 1 should actually read: Any.Monster. I'll fix that. 多个消息一个文件中,但是root_type 只能有一个,解决方式如下: namespace TestApp; union Msg {TestObj, Hello} struct KV { key: ulong; value: double; } table TestObj { id:ulong; name:string; flag:ubyte = 0; list:[ulong]; kv:KV; } table Hello { id:uint; name:string; } table RootMsg{ any:Msg; } root_type RootMsg;

具体样例可以参见:https://github.com/DavadDi/study_example/tree/master/flatbuffers/multi_table

4. enum不生成name的前缀
---------------------------

flatc -c --no-prefix -b aa.fbs

5. 其他问题
----------------------------

enum的默认值只能从0开始

由于table中的字段全部为可选,因此所有返回指针的地方都必须判断是否为空指针
#define STR(ptr) (ptr!=nullptr)?ptr->c_str():""
std::string = STR(user_info->user_name());

posted on   深入浅出eBPF  阅读(1614)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示