What am I doing wrong with `unsafe_wrap()`?

You didn’t root r here, so it likely got garbage collected before the display call. You need to wrap all code which references r by pointer with GC.@preserve:

julia> function f()
          r = Ref(tuple(5.0, 2.0, 1.0, 6.0))
          GC.@preserve r begin
              p = Base.unsafe_convert(Ptr{Float64}, r)
              u = unsafe_wrap(Array, p, 4)
              display(u)
          end
          return nothing
       end
f (generic function with 1 method)

julia> f()
4-element Vector{Float64}:
 5.0
 2.0
 1.0
 6.0

Also note that you can’t leak u from this function without also ensuring r is rooted somehow. I’d recommend checking out the ffi section of the manual:

https://docs.julialang.org/en/v1/manual/calling-c-and-fortran-code/

2 Likes