COMMUNITY

Use a Cpp function in my Haxe Code

Hello, everybody,

I am currently trying to write a program that can access (“use”) C++ code.
Unfortunately I can’t find any really “beginner-friendly” guides.

Could someone show me a “Hello World, I am C++ Code” program as a simple case ?

Roughly something like this:

Haxe:

    public function main()
    {
     trace(Cpp.Hello("foo"));
    }

Cpp.cpp:

     void print(const char* input)
                 {
                   cout << "hello" << input << endl;
                 }

Thanks a lot already

http://old.haxe.org/doc/cpp/ffi

or

1 Like

Hi, you can try something like this.

Create Test.h file:

#ifndef __TEST_H
#define __TEST_H

#include <iostream>

class Test {
public:
	Test() {}

	int add(int a, int b) {
		return a + b;
	}


	void print(const char* input){
		std::cout << input << std::endl;
	}

	~Test() {}
};
#endif

Create Main.hx in the same directory:

import cpp.ConstCharStar;
import cpp.Star;

class Main {
	static function main() {
		final testPointer = Test.create();

		trace(testPointer.add(10, 20));

		testPointer.print(ConstCharStar.fromString("Hello World"));
		testPointer.alternatePrint("Hello World 2");

		testPointer.delete();


		final test = Test.make();
		test.print("I'm not a pointer");
	}
}

@:structAccess
@:unreflective
@:include('./Test.h')
@:native('Test')
extern class Test {
	@:native('new Test')
	public static function create():Star<Test>;

	@:native('Test')
	public static function make():Test;

	public function add(a:Int, b:Int):Int;
	public function print(input:ConstCharStar):Void;

	@:native('print')
	public inline function alternatePrint(input:String):Void {
		untyped __cpp__('{0}->print({1}.c_str())', this, input);
	}

	@:native('~Test')
	public function delete():Void;
}

Now, we need to compile and execute our program: haxe -main Main -cpp .\out -cmd out\Main.exe

As a result, you should see:

Main.hx:8: 30
Hello World
Hello World 2
I'm not a pointer

Hope it helps you to start!

1 Like

Just to assure you this is not a beginner-friendly problem so there are probably no beginner-friendly guides. While it is possible as pointed out by the replies above, you may encounter a bucket of limitations/obstacles in the process. Passing arguments / return values is one of them, you need to tackle type compatibility such as c-style string vs haxe string, c byte array vs haxe bytes, functions/closures, etc. and GC is another big topic.