Skip to content

Instantly share code, notes, and snippets.

@airstruck
Forked from CapsAdmin/sdl luajit threads.lua
Created December 2, 2017 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airstruck/0bf7b5be249b5eeb5572176c57030f41 to your computer and use it in GitHub Desktop.
Save airstruck/0bf7b5be249b5eeb5572176c57030f41 to your computer and use it in GitHub Desktop.
local ffi = require("ffi")
local lua = require("luajit")
local sdl = require("SDL2")
local message_type = "struct {uint8_t*to_ptr; size_t to_len; uint8_t*from_ptr; size_t from_len;} *"
local state = lua.L.newstate()
lua.L.openlibs(state)
local ok = lua.L.loadstring(state, [[
local ffi = require("ffi")
ffi.cdef("void* malloc(size_t size);")
local data_struct = ffi.typeof("]] .. message_type .. [[")
local main = function(data)
local ok, msg = pcall(function()
data = ffi.cast(data_struct, data)
--sdl = loadfile("]]..R("lua/build/SDL2/SDL2.lua")..[[")()
local ret = load(ffi.string(data.to_ptr, data.to_len))(sdl)
local chars = ffi.C.malloc(#ret)
ffi.copy(chars, ret)
data.from_ptr = chars
data.from_len = #ret
end)
if not ok then
io.write(msg)
return 1
end
return 0
end
return tonumber(ffi.cast("intptr_t", ffi.cast("int (*)(void *)", main)))
]])
if ok ~= 0 then
print(ffi.string(lua.tolstring(state, -1, nil)))
return
end
lua.pcall(state, 0, 1, 0)
local func_str = [[
local sleep = os.clock() + 0.5
while true do
if os.clock() > sleep then
break
end
end
return "hello from thread"
]]
local data_struct = ffi.typeof(message_type)
local thread_func = ffi.cast("int (*)(void *)", lua.tointeger(state, -1))
local thread_data = ffi.cast(data_struct, ffi.C.malloc(ffi.sizeof(data_struct)))
local func_chars = ffi.C.malloc(#func_str)
ffi.copy(func_chars, func_str)
thread_data.to_ptr = func_chars
thread_data.to_len = #func_str
thread_data.from_ptr = nil
thread_data.from_len = 0
local thread = sdl.CreateThread(thread_func, "test", ffi.cast("void *", thread_data))
event.AddListener("Update", "", function()
local data = thread_data.from_ptr
if data ~= nil then
local ret = ffi.string(thread_data.from_ptr, thread_data.from_len)
-- thread finished
print(ret)
ffi.C.free(data)
return event.destroy_tag
end
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment