2016-04-14 9 views
2

LuaJIT FFIライブラリでは、構造体はinitialized from tablesです。反対を行う簡単な方法はありますか?明らかに任意の特定の構造体については、テーブルに変換する関数を書くのは簡単ですが、フィールドを繰り返す必要があります。私はパフォーマンスについて特に気にしませんが、これはデバッグ専用です。テーブルへのLuaJIT FFI構造体の変換

答えて

3

ffi.typeinfoを使用するLuaライブラリffi-reflectを使用すると、内部ctype情報を読み取って構造体のフィールド名のリストを取得できます。

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) 
関連する問題