使用包含来自二进制文件的数据的许多字段来初始化Julia类型 [英] Initializing Julia type with many fields containing data from binary file

查看:85
本文介绍了使用包含来自二进制文件的数据的许多字段来初始化Julia类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的类型有很多字段(想想几百个).

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

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

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])

现在,我正在从二进制文件读取数据.二进制文件遵循一个规范,使得第一个4字节的值具有特定含义,第二个值具有其他含义,依此类推.

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.

键入30分钟后,我创建了一个类型,其所有字段都与二进制文件规范相对应.这些字段的顺序与二进制文件中相应值的显示顺序相同.

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.

我真正想要的是不必键入300行代码即可初始化对象:

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
           [...])

在C中进行设置后,只需使用2-3行代码即可将二进制数据fread()转换为结构.有什么方法可以在朱莉娅中模拟出这种轻松性吗?

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?

推荐答案

此代码段可能有帮助:

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

因此,您可以创建自己的类型,并假设它的所有部分都很简单,那么它将起作用.但是,如何在不提前知道多长时间的情况下读取ASCIIString?这在C语言中也不起作用.您只能以这种方式读取基本位类型.

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.

这篇关于使用包含来自二进制文件的数据的许多字段来初始化Julia类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆