Sharing Functions with Lua and BmaxNG

Started by GW, June 15, 2017, 05:10:46

Previous topic - Next topic

GW

[There really ought to be a code archives for this kind of post. hint, hint]

This tip is for BMaxNG and the zeke Luajit module, both maintained by Brucey.

Lua doesn't have any builtin Sign() function and handling the function inside lua was killing the performance of my script. 
The solution was to expose a function from Bmax to lua using the FFI.


1) Create a C file and inside put your function
Code (language C) Select


__declspec(dllexport) double c_sign(double x)
{
   return (x>0.0)-(x<0.0);   
}

Notice the dllexport part. this tells gcc that the function is exposed at the same level as the C standard library.
2) In your Bmax project you'll want to create a reference to the function like normal:
Code (language BlitzMax) Select

import "my_c_functions.c"
extern
   function c_sign:double(x:double)
endextern



3) Then in Lua, You need to declare the format of the function like:
Code (language BlitzMax) Select

local ffi = require("ffi")

ffi.cdef[[
double c_sign(double x);
]]
function sign(x)
   return ffi.C.c_sign(x)
end

Now you can use the sign function in lua that's not slow as hell.
This same method can be used in Vanilla Bmax, but there may be some extra steps because bcc mangles the name. you can look at the top of the generated assembly file to view the new name. It's been many years since I did it, so I don't recall all of the steps for classic BMax.

Qube

Quote[There really ought to be a code archives for this kind of post. hint, hint]
Created, created :)
Mac Studio M1 Max ( 10 core CPU - 24 core GPU ), 32GB LPDDR5, 512GB SSD,
Beelink SER7 Mini Gaming PC, Ryzen 7 7840HS 8-Core 16-Thread 5.1GHz Processor, 32G DDR5 RAM 1T PCIe 4.0 SSD
MSI MEG 342C 34" QD-OLED Monitor

Until the next time.