How do I define a pointer to a variable or list element in Julia? I have tried reading some resources but I am really confused about using a pointer in Julia.
You cannot have a pointer to a variable—unlike C/C++, Julia doesn't work like that: variables don't have memory locations as part of the language semantics; the compiler may store a variable in memory (or in a register), but that's none of your business 😁. Mutable objects, however, do generally live in memory and you can get a pointer to such an object using the pointer_from_objref
function:
pointer_from_objref(x)
Get the memory address of a Julia object as a
Ptr
. The existence of the resultingPtr
will not protect the object from garbage collection, so you must ensure that the object remains referenced for the whole time that thePtr
will be used.This function may not be called on immutable objects, since they do not have stable memory addresses.
See also:
unsafe_pointer_to_objref
.
Why the awful name? Because, really why are you taking pointers to objects? Probably don't do that. You can also get a pointer into an array using the pointer
function:
pointer(array [, index])
Get the native address of an array or string, optionally at a given location
index
.This function is "unsafe". Be careful to ensure that a Julia reference to
array
exists as long as this pointer will be used. TheGC.@preserve
macro should be used to protect thearray
argument from garbage collection within a given block of code.Calling
Ref(array[, index])
is generally preferable to this function as it guarantees validity.
This is a somewhat more legitimate use case, especially for interop with C or Fortran, but be careful. The interaction between raw pointers and garbage collection is tricky and dangerous. If you're not doing interop then think hard about why you need pointers—you probably want to approach the problem differently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With