Initializing Julia type with many fields containing data from binary file

 ̄綄美尐妖づ 提交于 2019-12-25 03:24:44

问题


I have a type with many fields (think hundreds).

The constructor system in Julia is fine for when I'm working with small types, but you can imagine how unwieldy this gets when I'm working with a massive object:

type Bar
  a:Int32
  b:Int32
  c:Int32
  d:Int32
  e:Float32
  f:Uint8
  g:Int64
  h:ASCIIString
  # ...
end

bar = Bar(1, 2, 3, 4, 5, 1.1, 64, 2147483648, "Wall of text", [hundreds more])

Now, I'm reading data from a binary file. The binary file follows a specification such that the first 4-byte value has a specific meaning, the second value another meaning, etc etc.

After 30 minutes of typing, I have created a type with all the fields corresponding the binary file specification. The fields are in the same order as the corresponding values would appear in the binary file.

What I would really like is to not have to type 300 lines of code to initialize the object:

bar2 = Bar(# here I describe what 'a' is
           read(f, Int32, 1)[0],
           # here I describe what 'b' is
           read(f, Int32, 1)[0],
           [...],
           # here I describe what 'j' is
           read(f, ASCIIString, 1)[0],
           [...],
           # this is getting long and tedious
           [...])

With my setup in C, I can fread() the binary data into a struct using just 2-3 lines of code. Is there a way I can emulate that ease in Julia?


回答1:


This code snippet might help:

immutable TwoFloats
    f1::Float32
    f2::Float32
end
newtwofloats = reinterpret(TwoFloats, rand(Uint8, 8*2))
# Gives an array with two elements of type TwoFloats
dump(newtwofloats[1])  # Print them...
dump(newtwofloats[2])  # ... out

So you could create your type, and assuming all the parts of it are simple, it would work. How can you read in an ASCIIString though, without knowing ahead of time how long it is? That doesn't work in C either. You can only read in basic bit types this way.



来源:https://stackoverflow.com/questions/25276189/initializing-julia-type-with-many-fields-containing-data-from-binary-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!