Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define a pointer in julia?

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.

like image 461
bitWise Avatar asked Dec 01 '19 12:12

bitWise


Video Answer


1 Answers

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 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.

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. The GC.@preserve macro should be used to protect the array 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.

like image 153
StefanKarpinski Avatar answered Oct 13 '22 04:10

StefanKarpinski