+2 votes

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.

in Engine by (14 points)

1 Answer

+4 votes

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.

by (29,090 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.