Callback to haxe function from extern cpp class

I’ve integrated a c++ game engine to my haxe project (via the cpp.Pointer and extern class stuff) and because of the structure of the engine (and because I don’t want to hack around too much with the code) I need a way to “capture” the main loop.

I am a very beginner with cpp. I tried to pass a function reference or pointer to the cpp lib, but I get some errors or in short: i have no plan what i should do. Maybe someone can explain me a little or give me a hint what I should try to pass the haxe function reference to the cpp code and how i can call this function from the non-haxe cpp side.

I tried something like that:

On initializing the extern class I pass the haxe function to the constructor.

The extern cpp class then should pass it to a member function variable.

#include <functional>
std::function<void(void)> mycallback = haxe_function;

And in the engine’s main loop i want to callback. haxe_function();

Problem is probably, that the haxe types are different e.g. a haxe function is not a standard cpp function, so it’s not easy to interact with cpp code.

Thanks in advance.

UPDATE: Aha, I can include hxcpp in the engine, this should make the interaction way easier.

Just for the record and if someone is looking for this solution too how to pass a function pointer from haxe to c++ to receive a callback from an extern c++ class/library.

//Main.hx
 public static function callback():Bool
 {
 trace("callback from extern c++ lib");
 return true;
 }
 
 public function new()
 {
 var entry = Entry.create();
 var app = entry.value.startApplication( untyped __cpp__ ("callback") );
 }


//YourExternBindings.hx

extern class Entry
{
 @:native("new Entry")
 public static function create():cpp.Pointer<Entry>;
 public function startApplication(cb:cpp.Callable<Void->Bool>):cpp.Pointer<ExternApplication>;
}


//and on the cpp side

 void Entry::startApplication(bool (*cb)())
 {
               cb(); // calling back to haxe code
 }

I had to return bool or int because on the cpp side void != Void, float != Float (cannot cast Void to void error)

UPDATE: but this works

@:void public static function callback():Void

2 Likes

haxe’s Float is C++'s double (Float32 is float)