fficlass.lua 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. --[[
  2. FFIClass system
  3. @author : Siapran Candoris
  4. For LuaJIT's FFI struct-based classes.
  5. ]]--
  6. local class = require("class")
  7. local ffi = require("ffi")
  8. local rawget = rawget
  9. local c_id = 0
  10. local function make_C_identifier( )
  11. local res = "id" .. c_id
  12. c_id = c_id + 1
  13. return res
  14. end
  15. local function ffi_make_meta( self )
  16. local c_id = make_C_identifier()
  17. ffi.cdef("typedef struct {" .. self.__cdef .. "} " .. c_id ..";")
  18. self.__ctype = ffi.metatype(c_id, self)
  19. self.__c_id = c_id
  20. end
  21. local function ffi_new(self, ...)
  22. if not rawget(self, "__ctype") then
  23. ffi_make_meta(self)
  24. end
  25. local res = self.__ctype()
  26. if self.init then
  27. res:init(...)
  28. end
  29. return res
  30. end
  31. local function ffi_new_array(self, nb_elem, ...)
  32. if not rawget(self, "__ctype") then
  33. ffi_make_meta(self)
  34. end
  35. local res = ffi.new(self.__c_id .. "[?]", nb_elem)
  36. if self.init then
  37. for i = 0, nb_elem - 1 do
  38. res[i]:init(...)
  39. end
  40. end
  41. return res
  42. end
  43. local function make_ffi_class(structdef, ...)
  44. local res = class(...)
  45. res.new = ffi_new
  46. res.new_array = ffi_new_array
  47. res.__cdef = structdef
  48. res.is_ffi_class = true
  49. return res
  50. end
  51. return make_ffi_class