How can I create a pointer to existing data using FFI LuaJIT?

I know that there are examples of creating pointers using FFI LuaJIT, but most of them do not point to existing data. One such example is here: How do I pass a pointer to LuaJIT ffi for use as an argument?

One thing that I have not been able to successfully do is create a pointer to an existing value. In order to have a pointer type, as far as I know, I must know that at some point in the future I want to point to a pointer to it, for example:

local vao = ffi.new("GLuint[1]")
gl.GenVertexArrays(1, vao)
gl.BindVertexArray(vao[0])

Here I know that glGenVertexArrays needs a pointer to vao, so I point it as GLuint [1]. In C, I would do something like the following:

GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

, vao, .

, ? , , ?

!

+4
3

cdata FFI.

, LuaJIT, , .

cdata; LuaJIT cdata ( ), type[1] .

+3

, cdata, , cdata . , , , Lua, C, malloc. Lua, .

, , rraallvv, , , seg-fault.

ffi.new("GLuint[1]"), GLuint Lua (LuaJIT ) , , GenVertexArrays() (1), GC , C-, (2) GenVertexArrays() , , .

, LuaJIT FFI , . ( ) C , . FFI, .

local function SafeHeapAlloc(typestr, finalizer)
  -- use free as the default finalizer
  if not finalizer then finalizer = ffi.C.free end

  -- automatically construct the pointer type from the base type
  local ptr_typestr = ffi.typeof("$ *", typestr)

  -- how many bytes to allocate?
  local typesize    = ffi.sizeof(typestr)

  -- do the allocation and cast the pointer result
  local ptr = ffi.cast(ptr_typestr, ffi.C.malloc(typesize))

  -- install the finalizer
  ffi.gc( ptr, finalizer )

  return ptr
end
+3

C, cdata,

void cdataToPointer(void *cdata, void **pointer) {
    *pointer = cdata;
}

// ...

void *mycdata = NULL;

lua_pushlightuserdata(L, &mycdata);
lua_setglobal(L, "__TEMP_USERDATA__");

luaL_dostring(L,
     "local ffi = require'ffi'\n"
     "ffi.cdef[[\n"
     "  void cdataToPointer(void *cdata, void **pointer);\n"
     "]]\n"
     "ffi.C.cdataToPointer(mycdata, __TEMP_USERDATA__)\n");
0

Source: https://habr.com/ru/post/1543804/


All Articles