Skip to content

Instantly share code, notes, and snippets.

@alendit
Created October 8, 2018 16:26
Show Gist options
  • Save alendit/b03242d7d1e602b013b20cbdbc5bc5a9 to your computer and use it in GitHub Desktop.
Save alendit/b03242d7d1e602b013b20cbdbc5bc5a9 to your computer and use it in GitHub Desktop.
`new_handle` / `from_handle` example script
// compile with g++ -fpic -shared handle.cpp -o libhandle.so
#include <cstdint>
extern "C" {
using LuaHandle = uint64_t;
LuaHandle maybe(LuaHandle h, bool ret) {
if (ret) return h;
return 0;
}
}
local ffi = require 'ffi'
ffi.cdef [[
uint64_t maybe(uint64_t handle, bool ret);
]]
local hlib = ffi.load("./libhandle.so")
local io = require 'io'
local res = {}
local res_cnt = 0
jit.opt.start("hotloop=10")
local holder = {}
local holder_cnt = 0
for i=1, 100 do
holder_cnt = holder_cnt + 1
holder[holder_cnt] = { a = i}
local handle = ffi.new_handle(holder[holder_cnt])
local ret = hlib.maybe(handle, i % 2 == 0)
if ret ~= 0 then
assert(i % 2 == 0)
res_cnt = res_cnt + 1
res[res_cnt] = ffi.from_handle(ret)
else
assert(i % 2 ~= 0)
end
end
print("Total of " .. #res .. " results")
for i = 1, #res do
if type(res[i]) == "table" then
print("res[" .. i .. "] = table element " .. res[i].a .. ".")
else
print("res[" .. i .. "] = number " .. res[i] .. ".")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment