GDNative dynamic_cast

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

Hi there,

I am experimenting with GDNative (C++) a and any attempt to use dynamic_cast causes a crash. My Setup is:

The base class:

class ItemBase : public Node2D {
GODOT_CLASS(ItemBase, Node2D);

public:

ItemBase();

virtual ~ItemBase();

static void _register_methods();

void _init();

ItemAppearanceDefinition get_appearance_definition();

virtual void __item_base();
};

The child class:

class Hay : public ItemBase {
GODOT_CLASS(Hay, Node2D)

private:

public:

Hay();

~Hay();

static void _register_methods();

void _init();

void _ready();

ItemAppearanceDefinition get_appearance_definition();

void __item_base() override;
};

The __item_base() method is registered by the register_method() and is used to ensure the node is subclass of the ItemBase.
Then somewhere in code:

auto item = get_node<Node2D>(item_path);
if (item->has_method("__item_base")) {
    Godot::print("yes, this is item base");
    auto base = (ItemBase*)item;
    Hay* hay = dynamic_cast<Hay*>(base);  // <= IT CRASH ON THE DYNAMIC CAST

    if (hay) {
        Godot::print("YES! THIS IS HAY!!!");
    }
} else {
    Godot::print("nope, this is not item base");
}

The stacktrace

handle_crash: Program crashed with signal 11
Dumping the backtrace. Please include this when reporting the bug on https://github.com/godotengine/godot/issues
[1] /usr/lib/haswell/libc.so.6(+0x43290) [0x7f4b3c9bf290] (??:0)
[2] /usr/lib/libstdc++.so.6(__dynamic_cast+0x44) [0x7f4b3c6f5534] (??:0)
[3] DroppedItem::_ready() (??:0)
[4] godot_variant godot::__wrapped_method<DroppedItem, void>(void*, void*, void*, int, godot_variant**) (??:0)
[5] godot() [0x1e91f92] (??:?)
[6] godot() [0x1e9407a] (??:?)
[7] godot() [0x32fce45] (??:?)
[8] godot() [0x382b129] (??:?)
[9] godot() [0x4396c3e] (??:?)
[10] godot() [0x32fe9e7] (??:?)
[11] godot() [0x32fe992] (??:?)
[12] godot() [0x32fe992] (??:?)
[13] godot() [0x32fe992] (??:?)
[14] godot() [0x33034ba] (??:?)
[15] godot() [0x333324f] (??:?)
[16] godot() [0x1b38ac0] (??:0)
[17] godot() [0x1b283ec] (??:0)
[18] /usr/lib/haswell/libc.so.6(__libc_start_main+0xd5) [0x7f4b3c9a6ba5] (??:0)
[19] godot() [0x1b2829e] (??:0)
-- END OF BACKTRACE --

Has anyone idea what is wrong?

Thank you for any response.

:bust_in_silhouette: Reply From: sash-rc

First use Object::cast<>() or get_node<>() with your class, not generic Node2D.

auto item = get_node<ItemBase>(item_path);

See also some notes: GitHub - godotengine/godot-cpp: C++ bindings for the Godot script API

This is exactly what I was looking for. Thank you very much :slight_smile:

elmordo | 2021-08-24 19:19