-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.lua
68 lines (57 loc) · 1.64 KB
/
demo.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
local modname = { 'demo','core'}
local concat = table.concat
local ok, ffi = pcall(require,'ffi')
if not ok then -- we must be in regular Lua, just use normal C module
local demo_hello = require(concat(modname,'.'))
return function()
return 'This is using the C API\n' .. demo_hello()
end
end
local demo_lib -- save reference to library/namespace
ffi.cdef[[
char* demo_hello(void);
]]
pcall(function()
if ffi.C.demo_hello then -- we're in a static binary, already linked, etc
demo_lib = ffi.C
end
end)
if not demo_lib then -- module not already linked, try to find and open dynamically
local dir_sep, sep, sub
local gmatch = string.gmatch
local match = string.match
local open = io.open
local close = io.close
for m in gmatch(package.config, '[^\n]+') do
local m = m:gsub('([^%w])','%%%1')
if not dir_sep then dir_sep = m
elseif not sep then sep = m
elseif not sub then sub = m end
end
local function find_lib(name)
for m in gmatch(package.cpath, '[^' .. sep ..';]+') do
local so_path, r = m:gsub(sub,name)
if(r > 0) then
local f = open(so_path)
if f ~= nil then
close(f)
return so_path
end
end
end
end
local function load_lib()
local so_path = find_lib(concat(modname,dir_sep))
if so_path then
return ffi.load(so_path)
end
end
demo_lib = load_lib()
end
if not demo_lib then
return nil,'failed to load module'
end
-- now we return the real guts of the module
return function()
return 'This is using the FFI API\n' .. ffi.string(demo_lib.demo_hello())
end