无法将向量添加到FlatBuffer表(Javascript)

时间:2016-08-23 13:02:31

标签: javascript node.js flatbuffers

我正在关注FlatBuffers Javascript tutorial,但我在向以下对象添加非标量项的向量时遇到问题:

namespace test;

enum Availability : byte {
  Unavailable = 0,
  Available = 1
}

table Channel {
  channelNumber:uint;
  myState:Availability = Unavailable;
}

table ControlChannel {
  channels:[Channel];
}

root_type ControlChannel; 

如您所见,根对象包含Channel个对象的向量。我成功生成了我的javascript代码,但在尝试创建一些测试数据时,似乎没有正确添加通道。这就是我试过的:

const fs = require('fs');
const flatbuffers = require('./flatbuffers').flatbuffers;
const test = require('./control-channel_generated').test;

// Create builder. The '1' is the 'initial size', whatever that means.
const builder = new flatbuffers.Builder(1);

// Create the first channel
test.Channel.startChannel(builder);
test.Channel.addChannelNumber(builder, 1);
const channel1 = test.Channel.endChannel(builder);

// Create another channel
test.Channel.startChannel(builder);
test.Channel.addChannelNumber(builder, 2);
test.Channel.addMyState(builder, test.Availability.Available);
const channel2 = test.Channel.endChannel(builder);

// Create a vector of the channels
const chans = [channel1, channel2];
const channels = test.ControlChannel.createChannelsVector(builder, chans);

// Create control channel and add the channels
test.ControlChannel.startControlChannel(builder);
test.ControlChannel.addChannels(builder, channels); // The resulting cc-test.data file is the same whether I comment this line or not
const controlChannel = test.ControlChannel.endControlChannel(builder);

// Control channel is finished
builder.finish(controlChannel);

// Create a buffer (to send it, write it etc)
const buf = builder.asUint8Array();
fs.writeFileSync('cc-test.data', buf);
console.log(`Data written to 'cc-test.data'.`);

这导致一个名为cc-test.data的文件包含缓冲区,无论我尝试添加多少个通道,缓冲区总是完全相同。我也试过像这样解析数据:

const fs = require('fs');
const flatbuffers = require('./flatbuffers').flatbuffers;
const test = require('./control-channel_generated').test;

// Parse the data as a new byte array
const data = new Uint8Array(fs.readFileSync('./cc-test.data'));
const buf = new flatbuffers.ByteBuffer(data);

// This is where all the magic happens
const controlChannel = test.ControlChannel.getRootAsControlChannel(buf);

// You can not iterate over the channels directly, you have to get it by index
console.log(`ControlChannel has ${controlChannel.channelsLength()} channels:`);

for (var i = 0; i < controlChannel.channelsLength(); i++) {
  const channel = controlChannel.channels(i);
  console.log(`Channel ${channel.channelNumber()} (Available: ${channel.myState()})`);
}

每次只打印 ControlChannel有0个频道。我错过了什么?

0 个答案:

没有答案