Created
October 8, 2018 16:26
-
-
Save alendit/b03242d7d1e602b013b20cbdbc5bc5a9 to your computer and use it in GitHub Desktop.
`new_handle` / `from_handle` example script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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