Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use Ptr instead of Ref

Tags:

julia

Based on the doc, Ptr{T} is

A memory address referring to data of type T. However, there is no guarantee that the memory is actually valid, or
  that it actually represents data of the specified type.

From the other hand :

 Ref{T}

  An object that safely references data of type T. This type is guaranteed to point to valid, Julia-allocated memory
  of the correct type. The underlying data is protected from freeing by the garbage collector as long as the Ref
  itself is referenced.

So my question is : Ref seems have the same use cases than Ptr and seems better than Ptr in any cases. Is there some rules on when should we use Ptr{T} instead of Ref{T} ?

like image 713
Julie96 Avatar asked Oct 21 '25 16:10

Julie96


1 Answers

It's useful when you're mixing C into Julia (no surprise because the doc page you're referencing is named "C interface"). Like you said, a Ref looks like a souped up Ptr guaranteed to have valid Julia-allocated memory handled by Julia's garbage collector. Ptr is more appropriate for wrapping pointers made and handled on the C side. The guidelines are written in a small section "When to use T, Ptr{T} and Ref{T}" in the "Calling C and Fortran Code" page:

In Julia code wrapping calls to external C routines, ordinary (non-pointer) data should be declared to be of type T inside the ccall, as they are passed by value. For C code accepting pointers, Ref{T} should generally be used for the types of input arguments, allowing the use of pointers to memory managed by either Julia or C through the implicit call to Base.cconvert. In contrast, pointers returned by the C function called should be declared to be of output type Ptr{T}, reflecting that the memory pointed to is managed by C only. Pointers contained in C structs should be represented as fields of type Ptr{T} within the corresponding Julia struct types designed to mimic the internal structure of corresponding C structs.

If you're doing pure Julia, you'll want to stick to Ref, though you won't need it routinely because references usually show up in mutable objects or struct fields with an abstract type. Ref is fairly useful in making an iterable a scalar in broadcasting and wrapping an immutable object in a mutable reference.

like image 141
BatWannaBe Avatar answered Oct 23 '25 08:10

BatWannaBe