pointer_from_objref

pointer_from_objref(object_instance)

Get the memory address of a Julia object as a Ptr. The existence of the resulting Ptr will not protect the object from garbage collection, so you must ensure that the object remains referenced for the whole time that the Ptr will be used.

Examples

  1. Get the memory address of a Julia object:

    julia> obj = "Hello, Julia!";
    julia> ptr = pointer_from_objref(obj);
    julia> ptr
    Ptr{UInt8} @0x000000011c3a2b90

    This example retrieves the memory address of the obj string.

  2. Use the obtained Ptr to access object memory directly:

    julia> obj = [1, 2, 3];
    julia> ptr = pointer_from_objref(obj);
    julia> unsafe_load(ptr)
    1

    Here, the unsafe_load function is used to directly access the memory location pointed to by ptr.

  3. Ensure object reference during Ptr usage:
    julia> obj = [4, 5, 6];
    julia> ptr = pointer_from_objref(obj);
    julia> unsafe_store!(ptr, 7);
    julia> obj
    1-element Vector{Int64}:
    7

    This example demonstrates that even though the object is modified using the Ptr, the object reference is still required to observe the changes.

Common mistake example:

julia> obj = [1, 2, 3];
julia> ptr = pointer_from_objref(obj);
julia> obj = "New object";
julia> unsafe_load(ptr)
ERROR: UndefRefError: access to undefined reference

In this example, the mistake is reassigning obj to a new object. Since the Ptr is still pointing to the old memory address, accessing it results in an error. Ensure that the object remains referenced throughout the Ptr usage to avoid such errors.

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: