In general, the lifeness of an object has to be bound to either a local scope or global variables. Additionally, the bound could be indirect through parent object(s).
If the object you want to keep alive is not directly global or easily tied to a scope, you need to store it in a parent object during the time you want to keep it alive. You can add or remove the reference to your object from this parent object to realize the lifetime you want. Such an object can be anything that you can store your references in and unless you have some special requirement you could just use an ObjectIdDict.
Now the only question left is how do you keep this parent object alive. Unless you want to do something fancy you should just keep it alive either in a global (store it to a global variable in julia) or a local scope (JL_GC_PUSH…). A global variable is more general while a local frame could be faster. Which one of these to use depends on your usecase.
What if the scope of the mutable struct is the C++ class, with all its methods. How should I go about it? Should I make the allocated mutable struct object global, as I have done here? :
jl_set_global(jl_current_module, jl_symbol("MutableStruct"), mutable_struct_constructor);
pointer_to_mutable_struct = jl_get_global(jl_symbol("MutableStruct"));
Also, what should I do to deallocate it, or to let know the GC that the object can be freed. Should I do something like this in the destructor of my C++ class:
jl_set_global(jl_current_module, jl_symbol("MutableStruct"), nullptr);
pointer_to_mutable_struct = nullptr;
Would this approach work to dynamically handle what I want the GC to collect or not? Would there be more elegant ways? Thanks again