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
-
Get the memory address of a Julia object:
julia> obj = "Hello, Julia!"; julia> ptr = pointer_from_objref(obj); julia> ptr Ptr{UInt8} @0x000000011c3a2b90This example retrieves the memory address of the
objstring. -
Use the obtained
Ptrto access object memory directly:julia> obj = [1, 2, 3]; julia> ptr = pointer_from_objref(obj); julia> unsafe_load(ptr) 1Here, the
unsafe_loadfunction is used to directly access the memory location pointed to byptr. - Ensure object reference during
Ptrusage:julia> obj = [4, 5, 6]; julia> ptr = pointer_from_objref(obj); julia> unsafe_store!(ptr, 7); julia> obj 1-element Vector{Int64}: 7This 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.