1

我是谷歌平面缓冲区的新手。

我正在尝试序列化一组对象,以便使用 nodeJS 在网络上传输它。

首先我创建了一个 fbs 文件并用 flatc 编译它:

namespace MyAlcoholist;

table Drink {
 drink_type_name: string;
 drink_company_name: string;
 drink_brand_name: string;
 drink_flavor_type_name : string;
 liquid_color_type_name : string;
 liquid_color_is_transparent : bool;
 alcohol_vol : float;
 calories_for_100g : uint;
 global_image_id: ulong;
 drink_flavor_id: ulong;
}

root_type Drink;

编译器生成了一个名为drink_generated.js.

然后我在 Nodejs 中创建了以下实用程序模块。

var flatbuffers = require('../js/flatbuffers').flatbuffers;
var builder = new flatbuffers.Builder(1);

var drink = require('../fbs/drink_generated').MyAlcoholist; // Generated by `flatc`.

function drinkArrayToIdl(drinkArray) {
drinkArray.forEach(function (element, index, array) {
    var drinkObj = element;
    drink.Drink.startDrink(builder);
    var drinkBrandName = builder.createString(drinkObj.drink_brand_name);
    var drinkCompanyName = builder.createString(drinkObj.drink_company_name);
    var drinkflavorTypeName = builder.createString(drinkObj.drink_flavor_type_name);
    var drinkTypeName = builder.createString(drinkObj.drink_type_name);
    var liquidColorTypeName = builder.createString(drinkObj.liquid_color_type_name);
    drink.Drink.addAlcoholVol(builder, drinkObj.alcohol_vol);
    drink.Drink.addCaloriesFor100g(builder,drinkObj.calories_for_100g);
    drink.Drink.addDrinkBrandName(builder,drinkBrandName);
    drink.Drink.addDrinkCompanyName(builder,drinkCompanyName);
    drink.Drink.addDrinkFlavorId(builder,drinkObj.drink_flavor_id);
    drink.Drink.addDrinkFlavorTypeName(builder, drinkflavorTypeName);
    drink.Drink.addDrinkTypeName(builder,drinkTypeName);
    drink.Drink.addGlobalImageId(builder,drinkObj.global_image_id);
    drink.Drink.addLiquidColorIsTransparent(builder,drinkObj.is_transparent);
    drink.Drink.addLiquidColorTypeName(builder,liquidColorTypeName);
    drink.Drink.endDrink(builder);
})
}

module.exports.drinkArrayToIdl=drinkArrayToIdl;

现在基于https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html我需要关闭缓冲区,builder.finish(var)然后使用builder.dataBuffer().

我在理解我需要提供什么 var 时遇到问题builder.finish(var)

我知道该函数endDrink()返回我可以调用以关闭缓冲区的变量,但它只是为了一杯饮料。我希望能够向该缓冲区插入许多对象。

那可能吗?我做对了吗?

任何有关该问题的信息将不胜感激。

4

1 回答 1

0

添加一个table Drinks { drinks:[Drink]; }并使其成为您的新root_type. 然后收集向量中的所有返回值endDrink,并用它创建一个Drinks表。

此外,将所有调用移至createStringbefore startDrink,因为不应嵌套对象。

于 2016-02-17T03:35:59.000 回答