How to return a C++ reference back to GDScript from a custom C++ module

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By wasabininja

Hi
I’m not exactly sure how to do this. Do I have to convert the pointer to an integer? or is there a better way to do this.

:bust_in_silhouette: Reply From: Zylann

If you want to pass a C++ object to GDScript, it has to derive from Object.

If it derives from Object, you should be able to return the pointer to it directly, and GDScript will take care of wrapping up its usage like a normal object (for example, nodes derive from Object. When you do get_node() it returns a pointer to the node).
Objects need to be freed manually once you finished using them, unless you derive from Reference.

If your object derives from Reference, it is a better idea to wrap it inside a Ref<T> container (even in C++ in general), and return that instead. This is how resource types are returned, for example the texture getter of Sprite is Ref<Texture> get_texture(). Contrary to Object, references are automatically freed once no variable holds a reference to them.

If your object does not derive from Object, then you’re on your own. You will have to either wrap it in an Object in order to get a more friendly API in GDScript, or convert it to an equivalent: for example, if your object is a std::map, you can convert it to a Dictionary.
In the worst case, you have to cast it to an int of the proper size (Variant integers should be 64 bits) and pass it like that as an opaque pointer, but it’s risky and unfriendly so you may want to prefer other options if that’s avoidable.