fficlass.lua 1.1 KB

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