Suppose I have a C code
int sum(int *a, int n){
int s = 0;
for(int i=0; i<n; i++){
s += a[i];
}
return s;
}
and I can call this from Julia as
julia> ccall((:sum, "./libsum.so"), Cint, (Ref{Cint},Cint), Cint[1,2,3], 3)
6
julia> ccall((:sum, "./libsum.so"), Cint, (Ptr{Cint},Cint), Cint[1,2,3], 3)
6
which of these two is the recommended form? The section Calling C and Fortran Code · The Julia Language suggests
For C code accepting pointers,
Ref{T}
should generally be used for the types of input arguments
but I have come across many libraries using Ptr{T}
as the argument type, with seemingly no difference in the outcome. My limited (And somewhat naive) understanding of this is that Ref{T}
ensures that the GC doesn’t clear the underlying memory, whereas Ptr{T}
offers no such guarantee. This would suggest that Ref{T}
is the safer option.
Could someone suggest the correct form here? And is there a reason to prefer Ptr
over Ref
in certain scenarios?