Haha how silly of me! Don't know how I overlooked unsafe_load(ptr)...
How odd, in the end I thought ::DataType and Type{T} doesn't emit different 
code... Guess it must have been obscured by something else.
But yeah, makes sense that this specializes differently.


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