Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing byte array from C to Lua

Tags:

arrays

lua

I'm trying to pass a byte array from C to lua. If I pass it as a string I cannot pass arrays that contain "0x00" (because it is interpreted as the end of the string). That's what I wrote so far:

C:

uchar hash[32];
memset(hash, 0, 32);

sha256_final(ctx, hash);
lua_pushstring(L, (const char*)hash);
return 1;

Lua:

local hash_str = shaFunctions.final(ctx)
local hash = {}
hash_str:gsub(".",function(c) table.insert(hash,string.byte(c)) end)

Is there a better way for passing a byte array from C to Lua? Thanks

like image 344
Ofa Avatar asked Jan 01 '26 00:01

Ofa


1 Answers

You can use lua_pushlstring() function.

This is the prototype:

void lua_pushlstring (lua_State *L, const char *s, size_t len);

and your code will look like this:

uchar hash[32];
memset(hash, 0, 32);

sha256_final(ctx, hash);
lua_pushlstring(L, (const char*)hash, 32);
return 1;
like image 50
Luiz Menezes Avatar answered Jan 02 '26 18:01

Luiz Menezes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!