unsafe_pointer_to_objref

unsafe_pointer_to_objref(p::Ptr)

Convert a Ptr to an object reference. Assumes the pointer refers to a valid heap-allocated Julia object. If this is not the case, undefined behavior results, hence this function is considered "unsafe" and should be used with care.

Examples

unsafe_pointer_to_objref(p::Ptr{T}) where T

Converts a Ptr to an object reference of type T. This function assumes that the pointer p refers to a valid heap-allocated Julia object. It is important to note that using this function incorrectly can lead to undefined behavior, hence it is considered unsafe and should be used with caution.

Example:

julia> p = ccall(:malloc, Ptr{Cvoid}, (UInt,), sizeof(Int64))
Ptr{Nothing} @0x0000000002d85640

julia> x = unsafe_load(p, 1)
0

julia> unsafe_store!(p, 1, 42)

julia> objref = unsafe_pointer_to_objref(p)
Ptr{Int64} @0x0000000002d85640

julia> objref[]
42

julia> unsafe_store!(p, 1, 100)  # Modifying the object through the pointer

julia> objref[]
100

julia> ccall(:free, Cvoid, (Ptr{Cvoid},), p)  # Freeing the allocated memory

In this example, we allocate memory using ccall and obtain a pointer p. We then use unsafe_pointer_to_objref to convert the pointer p to an object reference of type Int64. We can then access and modify the object using the object reference. Finally, we free the allocated memory using ccall.

Note: It is crucial to ensure that the pointer is valid and points to a heap-allocated Julia object before using unsafe_pointer_to_objref. Improper usage of this function can lead to memory errors and undefined behavior.

See Also

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: