c++使用 FlatBuffers 在二进制文件中写入具有循环依赖性的数据

标签 c++ flatbuffers

我正在尝试使用 FlatBuffers 将图形写入二进制文件。图由节点和边组成。每个节点至少有一条边,每条边由两个节点组成。

摘自 MyGraph.fbs:

namespace MyGraph;

table Node {
  edges:[Edge];
}

table Edge {
  startNode:Node;
  endNode:Node;
}

table Graph {
  allNodes:[Node];
}

root_type Graph;

现在我想创建一个简单的图形并将其写入字节文件:

FlatBufferBuilder fbb;
// create first node
auto node1mloc = DG::CreateNode(fbb, 0, 0);

// create second node
auto node2mloc = DG::CreateNode(fbb, 0, 0);

// create edge between first and second node
auto edgeloc = DG::CreateEdge(fbb, node1mloc, node2mloc);


// ???
// store the edge in the edges-vector of node1 and node2
// ???

// store nodes in graph
flatbuffers::Offset<Node> nodes[] = {node1mloc, node2mloc};

auto allNodes = fbb.CreateVector(nodes, 2);

auto graphloc = DG::CreateGraph(fbb, allNodes);

DG::FinishGraphBuffer(fbb, graphloc);


// write graph into file
auto buffer_pointer = fbb.GetBufferPointer();
SaveFile("myfile2.bin", reinterpret_cast<const char *>(buffer_pointer), fbb.GetSize(), true);



// load graph from file
string binData;
LoadFile("myfile2.bin", true, &binData);

auto graph = DG::GetGraph(binData.data());
cout << graph->allNodes()->size() << endl;
assert(graph->allNodes()->size() == 2);

问题是,在创建节点之后,我无法将边添加到节点 1 和节点 2 的边 vector 中。对于两种类型之间的这种循环依赖,是否有解决方案。

最佳答案

您不能在 FlatBuffer 中存储循环结构(它使用无符号偏移量强制子项总是在父项之前)。

但是,您可以存储 DAG。

要对循环结构进行编码,您必须为节点或边引用使用索引,例如

table Edge {
  startNode:uint;
  endNode:uint;
}

这意味着这些节点引用是 allNodes 的索引。

请注意,很少有允许图形的序列化格式,例如Protocol Buffers 和 JSON 都只允许树。

关于c++使用 FlatBuffers 在二进制文件中写入具有循环依赖性的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34068841/

相关文章:

c# - BulletPhysics - 更新单个对象

c++ - 尝试将 boost.serialization 包含到我的 VS 项目时遇到问题

c++ - 跟踪/查找对 printf 或 cout 的调用的快速方法(长期丢失的调试输出)

python - 如何处理非常大的位板

java - Flatbuffers:如何构建嵌套表?

c# - 尝试从 flatbuffer 的二进制文件访问 "LengthofTable"时出现 SystemAccessOutOfbound 异常

c++ - 将对象重置为初始状态的模式

c++ - 我可以将 FlatBuffers 序列化/反序列化为 JSON 吗?

schema - FlatBuffers 架构 : Vectors of unions

javascript - 使用 typescript 正确导入 FlatBuffers