It’s in memory — or in a memory-mapped file. How do I reinterpret at an offset 
in an array?

On March 23, 2015 at 5:03:47 PM, Tobias Knopp (tobias.kn...@googlemail.com) 
wrote:

Is the data in a file or already read into an array? If it is still in the file 
you can simply read the data using the read function. If the data is read as an 
Uint8 array you can use an immutable and reinterprete into it. This does 
however not work if the C-struct would contain fixed-size array data.

Cheers

Tobi



Am Montag, 23. März 2015 20:20:09 UTC+1 schrieb Sebastian Good:
I'm trying to read some binary formatted data. In C, I would define an 
appropriately padded struct and cast away. Is is possible to do something 
similar in Julia, though for only one value at a time? Philosophically, I'd 
like to approximate the following, for some simple bittypes T (Int32, Float32, 
etc.)

T read<T>(char* data, size_t offset) { return *(T*)(data + offset); }

The transliteration of this brain-dead approach results in the following, which 
seems to allocate a boxed Pointer object on every invocation. The pointer 
function comes with ample warnings about how it shouldn't be used, and I 
imagine that it's not polite to the garbage collector.


prim_read{T}(::Type{T},
data::AbstractArray{Uint8,  
1},
byte_number)  
=  
unsafe_load(convert(Ptr{T},  
pointer(data,
byte_number)))

I can reinterpret the whole array, but this will involve a division of the 
offset to calculate the new offset relative to the reinterpreted array, and it 
allocates an array object. 

Is there a better way to simply read the machine word at a particular offset in 
a byte array? I would think it should inline to a single assembly instruction 
if done right.
    

Reply via email to