UnsafePointers.jl: Convenient (but unsafe) pointer accesses

Sometimes you need to interface with a C library. Sometimes that C library gives you pointers to structs containing pointers to arrays of pointers to…

# In C you do this:
p->second_field[3] = 9

# In Julia you do this:
unsafe_store!(unsafe_load(unsafe_load(p) + fieldoffset(eltype(p), 2)) + 3*sizeof(fieldtype(eltype(p), 2)), 9)

# Now you can do this:
q = UnsafePtr(p)
q.second_field[][4] = 9

This package exports one type, UnsafePtr{T}, which behaves similarly to a regular Ptr{T} but has some convenient (but unsafe) pointer access semantics.

Also Array(q, dims...), view(q, start:stop), String(q) are various ways to reinterpret array data.

Under the hood we are calling the unsafe_* family of functions. This library is a way of declaring once that you know what you are doing, and thereafter getting nice syntax for unsafe operations.

7 Likes

Hm, I wonder I we can interface that with UnsafeArrays.jl …

Also consider GitHub - RelationalAI-oss/Blobs.jl: Binary blobs with on-the-fly pointer patching