I have a question regarding ccall
, Ptr
, Ref
and pointer_to_objref
.
Let’s say I have a function that is like so
mutable struct UserData
x::Int
end
function foo(bar, userdata, err)
ccall((:foo, liblibrary), Cvoid, (Ptr{Cvoid},), userdata)
end
Is there any difference between the following code? If so, can someone elaborate on what the difference is?
userdata = UserData(1)
r = Ref(userdata)
x = foo(r)
And
userdata = UserData(1)
p = pointer_to_objref(userdata)
x = foo(p)
The documentation says
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 toBase.cconvert
.
Why does the documentation say “generally be used for types of input arguments”? What would be exceptions to this general rule? In what situations would it be appropriate to call pointer_to_objref
on an instance of a mutable Julia struct?