q66 / cffi-lua

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

Structure element assignment by value through array or pointer #7

Closed vsergeev closed 3 years ago

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

ffi.cdef[[
typedef struct point {
    int x;
    int y;
} point_t;
]]

local mt = {
    __tostring = function (self)
        return string.format("Point<%d, %d>", self.x, self.y)
    end,
}

Point = ffi.metatype("point_t", mt)

ffi.cdef[[
void *malloc(size_t size);
]]

local buf = ffi.C.malloc(ffi.sizeof(Point) * 32)
local points = ffi.cast(ffi.typeof("$ *", Point), buf)

points[0].x = 1
points[0].y = 2
print(points[0]) --> Point<1, 2>

print(Point(1, 2)) --> Point<1, 2>

points[0] = Point(1, 2) --> expected: no error, get: cannot convert 'struct point' to 'struct point'
print(points[0]) --> Point<1, 2>

Error occurs when assigning a structure array element by value through a pointer. Same error occurs for assignment through a fixed size array, e.g. local points = ffi.new("point_t [32]").

q66 commented 3 years ago

should be fixed now; and thanks for testing these, if there's anything the project needs right now it's various cases like this being tested and included into the testsuite (to avoid later regressions; it's really easy to mess things up as far as these kinda semantics are concerned)

vsergeev commented 3 years ago

No problem. cffi-lua is an awesome module, and it seems very close to parity with the LuaJIT FFI. I've been investigating the performance of running LuaRadio -- which relies heavily on the FFI -- under vanilla Lua, mostly out of curiosity. I think I will have a handful more test cases for you.