Unsafe_copyto! in function body problem

julia> function copy_bits(s::String)  
           assert(sizeof(s)>=8)
           res = UInt(0xffff)  # WARNING! Don't try to use zero(UInt)! 
           p=reinterpret(Ptr{UInt8}, pointer_from_objref(res))
           unsafe_copyto!(p, pointer(s), 8)
           ntoh(res)
       end;

julia> s = "abcdefgh"
julia> copy_bits(s)
0xffff000000000000  # this is bad

Now I just copy paste same code and add 3 comments

julia> # function copy_bits(s::String)  
         #  assert(sizeof(s)>=8)
           res = UInt(0xffff)  # WARNING! Don't try to use zero(UInt)! 
           p=reinterpret(Ptr{UInt8}, pointer_from_objref(res))
           unsafe_copyto!(p, pointer(s), 8)
           ntoh(res)
       # end;
0x6162636465666768  # this is good

why?

macro is working too:

julia> macro copy_bits(s::String)  
           assert(sizeof(s)>=8)
           res = UInt(0xffff)  # WARNING! Don't try to use zero(UInt)! 
           p=reinterpret(Ptr{UInt8}, pointer_from_objref(res))
           unsafe_copyto!(p, pointer(s), 8)
           ntoh(res)
       end
@copy_bits (macro with 1 method)

julia> @copy_bits("abcdefgh")
0x6162636465666768

I think the answer is “don’t do this”. See: https://github.com/JuliaLang/julia/issues/15857 and note that this will be explicitly forbidden in Julia v0.7.

2 Likes

Thanks for good hint! :slight_smile:
(and maybe wrong answer?)