0

以下の例では、BinData::Array 要素を含む新しい BinData::Record を作成でき、そのクラス タイプの新しいオブジェクトからバイナリ文字列を作成できます。ただし、そのバイナリ文字列から新しいオブジェクトをインスタンス化しようとすると、新しいオブジェクトが正しく作成されません。

require 'bindata'

class IntegerArray < BinData::Array
  uint16le initial_value: 0
end

class Test < BinData::Record
  integer_array :field
end

obj = Test.new
obj[:field] << 15

str = obj.to_binary_s

puts obj.inspect # {"field"=>[15]}
puts str.inspect # "\x0F\x00"
puts str.unpack("S<*") # 15

newobj = Test.read(str)

puts newobj.inspect # {"field"=>[]}

同じ結果で配列の initial_value を削除しようとしました。よろしくお願いします。

4

1 に答える 1

0

少し実験した後、次の解決策が機能することがわかりました。

require 'bindata'


class NumberArray < BinData::Array
  uint16le initial_value: 0
end

class Test < BinData::Record
  number_array :field, read_until: :eof
end

obj = Test.new
obj[:field].assign([1, 2, 3, 4, 5])

str = obj.to_binary_s

puts obj.num_bytes # 10
puts obj.inspect # {"field"=>[1, 2, 3, 4, 5]}
puts str.inspect # "\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00"

newobj = Test.read(str)
puts newobj.num_bytes # 10
puts newobj.inspect # {"field"=>[1, 2, 3, 4, 5]}

read_until: :eof配列フィールドを定義する際の の使用に注意してください。これがないと、読み取り操作はinitial_length( と相互に排他的ですread_until) の定義された値のみを読み取ります。

于 2014-04-28T16:18:59.163 に答える