I am in the middle of writing a small application that needs to read some complex binary messages in LuaJit.
I used a bit module and string.rep. However, all this is very cumbersome. I'm new to using LuaJit and I think it might be a lot easier to use FFI.
In C, I can declare a structure as follows:
struct mystruct { uint32_t field1; char field2[6]; uin64_t field3; short field4; } __attribute__(packed);
When reading LuaJit FFI it seems like you can declare
ffi.cdef[[ #pragma pack(1) struct mystruct { uint32_t field1; char field2[6]; uin64_t field3; short field4; }; ]]
Then I can create tinsel and access these fields:
local ms = ffi.new("mystruct") ms.field1 = 32;
But how do I convert this back to a lua string?
I tried this, but it seems he did not do what he wanted.
local s = tostring(ms)
and this:
local s = ffi.string(ms)
throws the following error: "bad argument # 1 to" string (cannot convert "struct mystruct" to "const char *") "
So I tried a throw:
local s = ffi.string(ffi.cast("char*", ms))
There is no error, but on the explorer it does not look right.
Matt source share