From type to ptr and back

Dear User,

I am calling a C library that ask for a void * data in a struct. Hence, I pass to this struct my julia variable a of Type Data using the void pointer b = pointer_from_objref(a).

However, later on, I want to modify the content of the field data of the C-struct.

Is there a way to get access to the content of the variable a using only b::Ptr{Void}?

Thank you for your help,

You can use unsafe_pointer_to_objref to restore a Julia object from a pointer, but you should keep in mind that this operation is “unsafe”, meaning it may cause a segfault if you access an invalid pointer. EzXML.jl uses this operation here: https://github.com/bicycle1885/EzXML.jl/blob/1c935a3fe11bfb0c0a707d8a213ecf5b4520c3af/src/node.jl#L296-L299.

Why not just use a? Note that you need to keep a or another reference to the data alive to avoid it from being garbage collected.

@bicycle1885, thank you for the hint. For @barche, this requires some serious change in my code. Cheers

In my case, a reference to the Julia object is not kept because it is totally okay to be garbage collected at any moment. A pointer to a Julia object will be set to null in the finalizer of the object, so the pointer cannot be a dangling pointer. I use this in order to keep the uniqueness of Julia objects for a C struct. That is, if a C struct has a pointer to a Julia object it is extracted using unsafe_pointer_to_objref and if one doesn’t have a non-null pointer a new Julia object is allocated. This kind of situation would be very rare, but unsafe_pointer_to_objref is actually in demand.