简体   繁体   English

在Julia中,如何在给定的内存位置重铸变量类型?

[英]In Julia, how do you recast variable type at a given memory location?

I'm using FortranFiles.jl to interface with files written by an old Fortran code. 我正在使用FortranFiles.jl与旧的Fortran代码编写的文件进行交互。 At one part of a given file, string arrays are cast as a single array of Float64's (or Float32's, depending) and stored as a Fortran record. 在给定文件的一部分,字符串数组被转换为Float64(或Float32,取决于)的单个数组,并存储为Fortran记录。

I can't seem to find documentation on how to do this in the manual or on-line. 我似乎在手册或在线中找不到有关如何执行此操作的文档。

Thus, to read the information, I'm using something like: 因此,要阅读信息,我正在使用类似以下内容的内容:

fid = FortranFile("myfile.dat")
read(fid, (Float64, 10))  # which actually represents 5x 16-char strings

How does one go about recasting the memory from an array of Floats, a constraint given due to using FortranFiles.jl and the way the file is stored, to a contiguous section of memory known to be characters by Julia? 如何将Floats数组(由于使用FortranFiles.jl和文件存储方式而给定的约束)的内存重铸到茱莉亚已知为字符的内存连续部分?

Think of something similar to turning a (void *) in C to (double *) , etc... 想想类似于将C中的(void *)变成(double *)等的事情...

Thanks. 谢谢。

Edit - Fixed inaccurate comment above about how many 16-char long strings were being read in. 编辑 -修正了上面关于读取16个字符长字符串的错误注释。

Krastanov, 克拉斯坦诺夫,

Thanks. 谢谢。 Using reinterpret was essentially the answer. 使用reinterpret本质上就是答案。 There were some nuances I discovered, however. 但是,我发现了一些细微差别。 (nb this is for Julia 1.1.0) (nb这是针对Julia 1.1.0的)

When dealing with reinterpreting between types of different sizes, you need to put the source in an array even for one element. 当处理不同大小的类型之间的重新解释时,您甚至需要将源放在一个数组中,即使对于一个元素也是如此。

Eg, reinterpret(UInt8, 1.23) won't work. 例如, reinterpret(UInt8, 1.23)将不起作用。 But reinterpret(UInt8, [1.23]) will work. 但是reinterpret(UInt8, [1.23])将起作用。 Not a problem for my example as read returns an array, but something I noticed when I was playing around at the REPL. 对于我的示例,这不是问题,因为read返回一个数组,但是当我在REPL上玩耍时,我注意到了一些东西。

Additionally, the Char type is a Unicode type and treated as a 32-bit data type, hence me using UInt8 above. 另外, Char类型是Unicode类型,被视为32位数据类型,因此我UInt8上面使用UInt8

The final answer looks like: 最终答案如下:

fid   = FortranFile("myfile.dat")
tmp   = read(fid, (Float64, 10))  # This return an array
chars = [Char(i) for i in reinterpret(UInt8, tmp)]

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

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