【问题标题】:How to merge clib functions into a table using LuaJIT and FFI?如何使用 LuaJIT 和 FFI 将 clib 函数合并到表中?
【发布时间】:2014-12-28 16:02:41
【问题描述】:

我在 Lua 中定义了一个表/对象。我正在尝试从 C-API dll 添加一些方法。我可以一次附上一个方法,但是有很多方法。下面代码的最后一行是我想做的事情。它应该将这些方法合并到Utilities 对象中,这样我就不必一次只做一个。我收到以下错误:

bad argument #1 to 'pairs' (table expected, got userdata)"  const char *

这里是一些示例代码:

Utilities = {}

--
-- Other Code that defines/attaches methods to Utilities
-- 

-- Define some methods from my utilities.dll
local ffi = require("ffi")
ffi.cdef[[
void LogThis(const char * format, ...);
]]

local utilities_ffi = ffi.load("utilities")

-- This works
utilities_ffi.LogThis("hello world")

-- merge the two tables together (this fails)
for k,v in pairs(utilities_ffi) do Utilities[k] = v end

FFI 必须返回一个用户数据对象。

【问题讨论】:

    标签: lua ffi luajit


    【解决方案1】:

    FFI 库对象不支持迭代;你不能在它们上面运行pairs。您必须手动为每个函数编写分配。

    另外请记住,直接从库对象访问 C 函数比将它们存储在表(甚至是局部变量)中并在那里访问它们更快。见the FFI tutorial的最后一段。

    【讨论】:

      【解决方案2】:

      试试这个:

      local function get(C, k)
        return C[k]
      end
      function merge(C1, C2)
         return setmetatable({}, {__index = function(t, k)
            local ok, ret = pcall(get, C, k)
            local v = ok and ret or C2[k]
            t[k] = v --cache it
         end})   
      end
      
      Utilities = merge(utilities_ffi, other_ffi)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-21
        • 1970-01-01
        • 2017-06-03
        • 1970-01-01
        • 1970-01-01
        • 2016-08-11
        • 1970-01-01
        相关资源
        最近更新 更多