Pass BM function pointers to C/C++ code

BlitzMax Forums/BlitzMax Programming/Pass BM function pointers to C/C++ code

TommyBear(Posted 2004) [#1]
Hi Mark,

Is it possible to pass BM function pointers into C or C++ code? I want to write a LUA module for BM but I need to be able to call back into BM.

Tommy.


TommyBear(Posted 2004) [#2]
Hats off to Mark. Here is the answer. I'll tell everyone something right now... BM is awesome and an extermely powerful GameDev solution. Okay here it is:

C Code
------

int (*callback)(const char *);

void RegisterCallback ( int (*infunc)(const char *) )
{
callback = infunc;
}

void CallMe ()
{
callback("Hello from C");
}

BM Code
-------

Strict

Import "test.c"

Extern
Function RegisterCallback ( functionptr@Ptr )
Function CallMe ()
End Extern

Function Test:Int( char:Byte Ptr )
' OMG I just got a call back
DebugStop
End Function

RegisterCallback( Test )
CallMe()


----- END ------

So what is this good for? Well I'll be writing a small LUA module for BM. You'll be able to export your internal BM functions to LUA and have those callable from script. Makes scripting of bots, AI, missions, save games etc extermely easily. Well done Mark!


marksibly(Posted 2004) [#3]
Hi,

That will work because BMX does auto function ptr->byte ptr casting, but a 'safer' way would be...

Extern
Function RegisterCallback( func( char:byte ptr ) )
End Extern

...which would prevent you from accidentally passing the wrong 'type' of function to RegisterCallback.


TommyBear(Posted 2004) [#4]
One more thing mark, is it possible to get a pointer to something from a c function? For instance I want to gt a lua_state * from one of the lua functions... is this possible?


marksibly(Posted 2004) [#5]
Hi,

I tend to just wrap these up in a 'byte ptr', eg:

Extern
Function GetLuaState:Byte Ptr()
End Extern

Local lua_state:Byte Ptr=GetLuaState()


TommyBear(Posted 2004) [#6]
Easy thanks.