# What am I doing wrong with \`unsafe\_wrap()\`?

**URL:** <https://discourse.julialang.org/t/what-am-i-doing-wrong-with-unsafe-wrap/75105>\
**Category:** General Usage\
**Created:** [January 24, 2022, 6:24am UTC](https://discourse.julialang.org/t/what-am-i-doing-wrong-with-unsafe-wrap/75105 "2022-01-24T06:24:50Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![simeonschaub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simeonschaub/32/216566_2.png) [@simeonschaub](https://discourse.julialang.org/u/simeonschaub)\
**Post date:** [January 24, 2022, 7:04am UTC](https://discourse.julialang.org/t/what-am-i-doing-wrong-with-unsafe-wrap/75105/2 "2022-01-24T07:04:22Z")

</div>

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
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/](https://docs.julialang.org/en/v1/manual/calling-c-and-fortran-code/)

---

_[View the full topic](https://discourse.julialang.org/t/what-am-i-doing-wrong-with-unsafe-wrap/75105)._
