简体   繁体   中英

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. 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.

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?

Think of something similar to turning a (void *) in C to (double *) , etc...

Thanks.

Edit - Fixed inaccurate comment above about how many 16-char long strings were being read in.

Krastanov,

Thanks. Using reinterpret was essentially the answer. There were some nuances I discovered, however. (nb this is for 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. But reinterpret(UInt8, [1.23]) will work. Not a problem for my example as read returns an array, but something I noticed when I was playing around at the REPL.

Additionally, the Char type is a Unicode type and treated as a 32-bit data type, hence me using UInt8 above.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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