Call C++ or hxcpp function/class from cppia?

Are there any examples of the Haxe/cppia code being able to call code from the host? Either C++ functions or functions from the host hxcpp?

I figured it out! I’m surprised this hasn’t been documented anywhere, is it because it was so obvious? Classes and functions from the host can be accessed from the cppia context using externs.

Host:

class Main {
    public static function main() {
        cpp.cppia.Host.runFile("myscript.cppia");
    }
}

@:headerCode("#include <iostream>")
class MyHostClass {
    public function new() {}
    public function doCppThing() {
        untyped __cpp__("std::cout << \"Hello World from C++\" << std::endl;");
    }
}

Cppia:

extern class MyHostClass { public function new(); public function doCppThing(): Void; }

class Script {
    public static function main() {
        var obj = new MyHostClass();
        obj.doCppThing();
    }
}
2 Likes

Cppia is sadly underused, mainly because there’s hardly any documentation.
I started documenting the very basics some year ago (Working with cppia - Working with cppia - Haxe programming language cookbook). This example maybe could be added there?

3 Likes

Shouldn’t the class names of Main be different? When I try it like that I get an endless loop, because the Cppia side starts with Main.main of the Host again and again. As soon as I rename the Cppia Main to e.g Script it works.

Oh nice! I read through that like 100 times desperately trying to find the answer, definitely think people would appreciate it being there. I didn’t realize anyone could contribute to it, so I’ll see if I can get this info posted there or on the API/manual, or feel free to do it yourself. :ok_hand:

Oh yikes, my bad. This was a simplification of what I had that I didn’t test. I’ll go ahead and update the original answer. Thanks for pointing this out!