1

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

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 个通道。我错过了什么?

4

0 回答 0