q66 / cffi-lua

A portable C FFI for Lua 5.1+
MIT License
176 stars 24 forks source link

Support additional C type serialization with `ffi.string()` #16

Closed vsergeev closed 3 years ago

vsergeev commented 3 years ago
local ffi = jit and require('ffi') or require('cffi')

local buf = ffi.new("uint8_t [3]", {0x61, 0x62, 0x63})
local p = ffi.cast("const uint8_t *", buf)

print(ffi.string(buf, ffi.sizeof(buf))) --> expected: abc, get: bad argument #1 to 'string' (cannot convert 'unsigned char [3]' to 'string')
print(ffi.string(p, 3)) --> expected: abc, get: bad argument #1 to 'string' (cannot convert 'unsigned char const *' to 'string')

ffi.cdef[[
struct foo {
    uint8_t a;
};
]]

local s = ffi.new("struct foo", 0x61)
local p = ffi.cast("const struct foo *", buf)

print(ffi.string(s, ffi.sizeof(s))) --> expected: a, get: bad argument #1 to 'string' (cannot convert 'struct foo' to 'string')
print(ffi.string(p, 1)) --> expected: a, get: bad argument #1 to 'string' (cannot convert 'struct foo *' to 'string')