【问题标题】:Converting LuaJIT FFI structs to tables将 LuaJIT FFI 结构转换为表
【发布时间】:2016-04-14 12:14:52
【问题描述】:

在 LuaJIT FFI 库中,结构体可以是initialized from tables。有没有一种简单的方法来做相反的事情?显然,对于任何 特定 结构,编写一个将其转换为表格的函数很容易,但它需要重复字段。我不是特别关心性能,这只是用于调试。

【问题讨论】:

    标签: lua luajit


    【解决方案1】:

    您可以使用ffi-reflect Lua 库,该库使用 ffi.typeinfo 读取内部 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)
    

    【讨论】:

      猜你喜欢
      • 2019-11-15
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 2014-07-20
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      相关资源
      最近更新 更多