How to correctly create a GDExtension?

Godot 4.3

I’ve created a C++ extension and hope that a specific function can be called when the object is released.The code is as follows:

CRObject.hpp

using namespace godot;
class CRObject: public RefCounted{
    GDCLASS(CRObject, RefCounted)
protected:
    static void _bind_methods();
public:
    CRObject();
    ~CRObject();

    GDVIRTUAL0(_dealloc);
    void dealloc();
};

CRObject.cpp

using namespace godot;

void CRObject::_bind_methods() {
    UtilityFunctions::print("Bind methods");
    ClassDB::bind_method(D_METHOD("dealloc"), &CRObject::dealloc);
    GDVIRTUAL_BIND(_dealloc);
}

CRObject::CRObject() {
    UtilityFunctions::print("Constructor");
}

CRObject::~CRObject() {
    UtilityFunctions::print("Destructor");
    dealloc();
}

void CRObject::dealloc(){
    UtilityFunctions::print("dealloc");
    if (GDVIRTUAL_CALL(_dealloc)){
        UtilityFunctions::print("call");
    } else {
        UtilityFunctions::print("no call");
    }
}

In the Godot editor, I created a subclass TestObj of CRObject. The code is as follows:

class_name TestObj
extends CRObject

func _dealloc():
	print("GD dealloc");

Finally, I created a TestObj object in main.gd. However, the _dealloc method of TestObj was not called.
main.gd

func _ready() -> void:
	var obj = TestObj.new()
	pass # Replace with function body.

Console output:

Bind methods
Constructor
Destructor
dealloc
no call
--- Debugging process stopped ---

How should I modify my program to ensure that the _dealloc method of TestObj is called correctly?

2 Likes

My guess is the script instance attached to the object has already been deleted during destruction. you should use the predelete notification to do any script side cleanup

2 Likes
void CRObject::dealloc() {
    UtilityFunctions::print("dealloc");
    GDVIRTUAL_CALL_NO_RETURN(_dealloc);
}

Does that even exist? I can’t find it in source or extension repo.

godot_cpp/classes/global_constants.hpp

sorry i meant GDVIRTUAL_CALL_NO_RETURN, even after building the gdextension and source on 4.3 i still don’t see it.