Page 1 of 1

HW/Lua calling C function with lightuserdata param ?

Posted: Sun Feb 14, 2021 2:51 am
by p-OS
My main problem with writing a HW Plugin is the fact that I have not much experience in actively writing C code. Especially all those pointer related syntax is confusing (compared to other os level languages like E, Pascal...).
Thus I try to play around with simple examples.

I was succesful with writing C functions that get and return numbers.
I also could export number and string constants.

Currently I try to exchange lightuserdata between HW and C.

As test case I want to expose exec.library AllocVec and FreeVec functions.

AllocVec:

Code: Select all

static SAVEDS int hw_allocvec(lua_State *L)
{
   void *memptr=NULL;

   lua_Number memsize = luaL_checknumber(L,1);

   memptr=AllocVec(memsize,0L);

   hwcl->LuaBase->lua_pushlightuserdata(L,memptr);

   return 1;
}                     

Code: Select all

mem=t.Allocvec(100000000) ; allocate 100 MB of Ram
DebugPrint(men) 
It works as expected. Mem is allocated. Output gives sth like "UserData: 0x1ef22c..."


Now I want to do a

Code: Select all

t.Freevec(mem)
But get an error. HW says it has to be a value of type number.
According to the HW manual, ToNumber can not only convert string to number, but also values of type #LIGHTUSERDATA.

My call now is:

Code: Select all

t.FreeVec(ToNumber(mem))
My C functioin looks like this:

Code: Select all

static SAVEDS int hw_freevec(lua_State *L)
{
   void *memptr=NULL;

   memptr = hwcl->LuaBase->lua_touserdata(L,hwcl->LuaBase->lua_tonumber(L,1));

   FreeVec(memptr);

   return 0;
}               

No errors, but memory is not freed.
How can I do it right ?
Probably my function is not ok. But I cannot find any luaL_checklightuserdata function or likewise...

Re: HW/Lua calling C function with lightuserdata param ?

Posted: Sun Feb 14, 2021 10:04 pm
by airsoftsoftwair
Don't use ToNumber() on a lightuserdata value. That doesn't make sense, neither in Hollywood nor in C code. So you should do something like this instead:

Code: Select all

; Hollywood code
t.Freevec(mem)

; C code
static SAVEDS int hw_freevec(lua_State *L)
{
   void *memptr=NULL;

   memptr = hwcl->LuaBase->lua_touserdata(L,1);

   FreeVec(memptr);

   return 0;
}