Accessing FFI cdata from the Lua C API

  • From: Florian Weimer <fw@xxxxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sun, 15 Jul 2012 19:02:15 +0200

I've got a C function which accepts Lua strings (using
luaL_checklstring) and I want to provide a variant which accepts cdata
(const char *, size_t) pairs.  I cannot call my functing using FFI
because it allocates Lua objects.

Right now, I'm using the code below, and it works as expected.  I know
I need to cache compile function and the ctype object.  But I wonder
if there is a completely different approach which is much simpler and
does not involve calling back into Lua.

  struct {
    const char *str;
    size_t len;
  } buffer;
  int ret;

  luaL_checkany(L, 2);
  luaL_checkany(L, 3);
  ret = luaL_loadstring
    (L, "local buffer, str, len = ...\n"
     "local ffi = require 'ffi'\n"
     "local ct = ffi.typeof 'struct{const char *str; size_t len;}*'\n"
     "buffer = ffi.cast(ct, buffer)\n"
     "buffer.str = str; buffer.len = len\n");
  switch (ret) {
  case 0:
  case LUA_ERRMEM:
    luaL_error(L, "out of memory");
  lua_pushlightuserdata(L, &buffer); /* func buffer */
  lua_pushvalue(L, 2);
  lua_pushvalue(L, 3);          /* func buffer str len */
  lua_call(L, 3, 0);

Other related posts: