Search code examples
lualuajit

Converting LuaJIT FFI structs to tables


In LuaJIT FFI library, structs can be initialized from tables. Is there a simple way to do the opposite? Obviously for any specific struct it's easy to write a function converting it to a table, but it requires repeating the fields. I don't particularly care about performance, this is only intended for debugging.


Solution

  • You can use the ffi-reflect Lua library which uses ffi.typeinfo to read the internal ctype info to get the list of field names of the struct.

    local ffi = require "ffi"
    local reflect = require "reflect"
    
    ffi.cdef[[typedef struct test{int x, y;}test;]]
    local cd = ffi.new('test', 1, 2)
    
    function totab(struct) 
      local t = {}
      for refct in reflect.typeof(struct):members() do
        t[refct.name] = struct[refct.name]
      end
      return t
    end
    
    local ret = totab(cd)
    assert(ret.x == 1 and ret.y == 2)