简体   繁体   English

使用包含来自二进制文件的数据的许多字段来初始化Julia类型

[英]Initializing Julia type with many fields containing data from binary file

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: 当我使用小型类型时,Julia中的构造函数系统非常适合,但是您可以想象一下,当我使用大型对象时,这会变得多么笨拙:

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. 二进制文件遵循以下规范:第一个4字节的值具有特定含义,第二个值具有另一种含义,依此类推。

After 30 minutes of typing, I have created a type with all the fields corresponding the binary file specification. 键入30分钟后,我创建了一个类型,其中所有字段都与二进制文件规范相对应。 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: 我真正想要的是不必键入300行代码即可初始化对象:

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. 通过在C中进行设置,我只需使用2-3行代码就可以将二进制数据读取fread()到结构中。 Is there a way I can emulate that ease in Julia? 有没有一种方法可以在朱莉娅中模仿出来?

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? 但是,如何在不提前知道多长时间的情况下读取ASCIIString? That doesn't work in C either. 这在C中也不起作用。 You can only read in basic bit types this way. 您只能以这种方式读取基本位类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM