Embedding NekoVM with compiled Haxe code into C/C++ application
Thursday, November 13th, 2008C++ calls Neko
You can see how to embed NekoVM and make calls from C/C++ application to the Neko code on this page.
To reacap. You create a (exported) neko function like this:
$exports.add = function(a, b) { return a + b; }
And call it from c++ like this:
int n_add(value module)
{
value n_add = val_field(module,val_id("add"));
if( val_is_function(n_add, 2) )
{
value ret = val_call2(n_add, 3, 5);
if(val_is_int(ret))
return val_int(ret));
}
return 0;
}
I will show an example of doing the same if you are writing your code in Haxe language and compiling it to Neko. The whole logic is the same. Only the structure of compiled neko module is a little different.
C++ calls Haxe
So let’s say you write a class like this in Haxe:
class MyTest
{
static function add(a:Float, b:Float) : Float
{
return a + b;
}
}
You compile it… if you want to see what is happening add the –neko-source to the compiler call so you can see the neko source that get’s generated from your haxe class. After some degree of banging my head looking at this and asking on mailing list and irc I found out that this is the way to do it.
The compiled haxe class exposes the __classes field. And the haxe class you made is a neko object with static functions and variables being accessible throught it. So how do you call the above then:
int add(value module)
{
value c = val_field(module,val_id("__classes"));
if( val_is_object(c))
{
value o = val_field(c,val_id("MyTest "));
if( val_is_object(o))
{
value f = val_field(o,val_id("add"));
if( val_is_function(f))
{
value ret = val_call2(f, 3, 5);
if(val_is_int(ret))
return val_int(ret));
}
}
}
return 0;
}
This is it. You can download, run and look at the haxe code where I used this (and reverse) in small example in my post Haxe & NekoVM meet PTK
.. about reverse. This post deals with calling functions from our c++ application into the embeded NekoVm only. If you are making something lika a game engine then you will probably need to call from the called neko functions back to c++ functions. I will post a tutorial about that too for Neko (but not Haxe – I haven’t figured clean way to do this with haxe, so I made sort of an ugly hack to get my stuff working).
