Classes Registration

NativeScript allows the users to write logic in C or C++ to create a binary library that can then be loaded and used by Godot’s GDScript, VisualScript or C# (in the godot-mono version) using the GDNative node but in order to be able to call NativeScript code from Godot, one has to register the code into Godot using the class registry within Godot.

Godot’s Class Registration

Godot’s GDNative can be loaded into Godot using the GDNativeLibrary resource that serves as bridge between the Golang compiled code and the GDNative node making possible to call methods and pass data through application boundaries from Godot into our native code.

In order to do so, we must compile out Golang code as a shared C library

go build -v -buildmode=c-shared -o <output_file_name>.so <path_to_sources>/*.go

Compiling our Golang library as C shared object is not enough, we have to explicitly register our code programatically in our code initialization. This traditionally is done within the init function on the main package.

// this will run on NativeScript initialization
func nativeScriptInit() {
    gdnative.Log.Info("Initializing nativescript from Go!")
    
    // class registration would follow using the gdnative.NativeScript.RegisterClass method    
}

// The "init()" function is a special Go function that will be called by the
// runtime when this library is initialized. Here we can register our Godot classes
func init() {
    // Set the initialization script that will run upon NativeScript initialization.
    // This function will handle using the NativeScript API to register all of our
    // classes so they can be used within Godot scripting languages.
    gdnative.SetNativeScriptInit(nativeScriptInit)
}

As shown above we pass a callback to the nativeScriptInit into the gdnative.SetNativeScriptInit method that will be used by the godot_nativescript_init C shared function directly from Godot engine on script initialization.

more than one function can be passed as argument to gdnative.SetNativeScriptInit, if more than one function is passed, they will be called in order

Methods Registration

To be able to call functions defined in our C shared library from within Godot scripting languages, we need to also register them within Godot NativeScript, this is done through the class registration attaching methods into it. Note that the functions we attach to the class doesn’t necessarily need to be a method from any Golang structure, do not worry if this isn’t completely clear yet, you will understand it much better then we run over our examples.

Properties and Signals registration

In the same way, we have to register our properties and signals, we will dig is way more detail when we analyze our sample projects.

full sample projects can be found in the examples directory on the library root