Safe Usage of UnsafeArrays

Is the following a “safe” usage of `UnsafeArrays?

struct SafeUnsafeArray{T, N} <: AbstractArray{T, N}
   A::UnsafeArray{T, N}
   _A::Vector{UInt8}
end

x = zeros(UInt8, 800)
ptr = Base.unsafe_convert(Ptr{Float64}, x)
u = UnsafeArray(ptr, (100,))
s = SafeUnsafeArray(u, x)

Now, may I pass s around some functions until I no longer need it, rather than use it only “locally” as suggested by the UnsafeArrays documentation?

NOTE: I’m fully aware of reinterpret, but it seems in some of my use-cases, UnsafeArrays is anywhere from 0 to 30% faster.

1 Like

what’s the benchmark?

Assemble a feature vector - anywhere between length 10 to 100000 - return it to the caller then the caller releases the array back into a pool. Similar tasks with forward and backward derivatives.

So basically I only use getindex and setindex

I find that in MWEs avoiding the allocation doesn’t help that much but when embedded in bigger tasks it can give 10-30% speed up. Not game changing but nice to have