Depending on your application, also consider
rc = ccall(:jl_reshape_array, Array{Test,1}, (Any, Any, Any), Array{Test,1}, vec, (1,))
This is the old implementation of reinterpret. Various caveats apply.
There is always a reason, but it’s not a good reason
I’d say skip the programmatic checks and do unsafe_load with pointer-casting, as @Mason said.
Remember that this cannot be done fast and safe and generic – choose two. You don’t care about “generic”, so all is fine.
As a word of warning: If you reinterpret with custom structs, then you must know the C memory layout rules and structure padding. Structure padding is scary.
Julia Bool
is especially scary in context of structure padding, since the language assumes that the leading 7 bit are zero. If they are not zero, then you are in undefined-behavior bats-in-your-nose land. You cannot check whether they are zero after reinterpretation, because the compiler knows that these 7 bit are zero and can optimize away your check. Such a malformed Bool can do things like
julia> struct X
b::Bool
end
julia> function flub(bs)
c = @inbounds bs[1].b
if c===true
1
elseif c===false
0
else
3
end
end
flub (generic function with 1 method)
julia> flub(reinterpret(X,[0x46]))
3
julia> reinterpret(X,[0x46])[1].b==false
true
julia> function flub2(bs)
c = if rand()==1337 Any[1][1] else @inbounds bs[1].b end
if c===true
1
elseif c===false
0
else
3
end
end
flub2 (generic function with 1 method)
julia> flub2(reinterpret(X,[0x46]))
0
edit: Messed up code example during copy-paste. It is supposed to demonstrate that:
- A malformed Bool can be neither true nor false
- However, it can become normalized to true/false when stored into memory, e.g. during Boxing due to type instability
- This means that behavior of malformed Bool is not well-defined – it depends on the state of type inference and optimizer/compiler internal state, and it is not correctly reproduced in the top-level REPL or in the interpreter.
This is not a bug in julia, its a bug in the user code that misunderstands the implicit structure padding of Bool and reinterpret.