# Unsafe\_wrap perform memory allocations

**URL:** <https://discourse.julialang.org/t/unsafe-wrap-perform-memory-allocations/123662>\
**Category:** General Usage\
**Tags:** array, c\
**Created:** [December 10, 2024, 3:04pm UTC](https://discourse.julialang.org/t/unsafe-wrap-perform-memory-allocations/123662 "2024-12-10T15:04:55Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![Mason](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mason/32/2423_2.png) [@Mason](https://discourse.julialang.org/u/Mason)\
**Post date:** [December 10, 2024, 3:36pm UTC](https://discourse.julialang.org/t/unsafe-wrap-perform-memory-allocations/123662/6 "2024-12-10T15:36:30Z")

</div>

Here’s a minimal demo of how to construct an `UnsafeArray` from a `Ptr`:

```julia-repl
julia> using UnsafeArrays

julia> let N = 10, T = Float64
           _ptr = Libc.malloc(sizeof(T) * N)
           ptr = convert(Ptr{T}, _ptr)
           
           A = UnsafeArray(ptr, (N,))
           A .= 1
           @show sum(A)

           Libc.free(ptr)
       end
sum(A) = 10.0

```

the important thing to know here is that you have to call `UnsafeArray(::Ptr{T}, ::NTuple{N, Int})` to construct an `UnsafeArray{T, N}`. For some reason they don’t have a method for `UnsafeArray{T, N}(::Ptr, dims...)`. That’s why I did the `convert` step in the above code.

> [@Sergey](#):
>
> But im using c++ to call julia and have pure messaging (dot get correct way to catch exceptions, `JL_TRY` is strange - it could be used only once)

I’d recommend that at least while debugging your code and learning to make it work, you run your code within julia. It’ll make it easier to get error messages that make sense and get people to help you.

See also [Please read: make it easier to help you](https://discourse.julialang.org/t/please-read-make-it-easier-to-help-you/14757)

---

_[View the full topic](https://discourse.julialang.org/t/unsafe-wrap-perform-memory-allocations/123662)._
