如何将指针传递到LuaJIT ffi中以作为输出参数?

假设有以下的 C 代码:

struct Foo { int dummy; }
int tryToAllocateFoo(Foo ** dest);

...如何在 LuaJIT 中实现以下功能?

Foo * pFoo = NULL;
tryToAllocateFoo(&pFoo);
点赞
用户12048
用户12048
local ffi = require 'ffi'

ffi.cdef [[
  struct Foo { int dummy; };
  int tryToAllocateFoo(Foo ** dest);
]]

local theDll = ffi.load(dllName) -- 导入名为 dllName 的动态链接库

local pFoo = ffi.new 'struct Foo *[1]' -- 定义一个指针数组
local ok = theDll.tryToAllocateFoo(pFoo) -- 将 pFoo 的地址传入函数 tryToAllocateFoo

if ok == 0 then -- 假设成功时返回 0
  print('dummy ==', pFoo[0].dummy) -- 输出结构体 Foo 的 dummy 字段的值
end
2012-12-23 22:01:53