lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi list,

I'm trying to improve the Pallene installer and one of the things I
want to do is create a shared library (installable via Luarocks) that
exports low-level C functions. Below I have a minimal example.
The mylib.c exports a C function "mylib_foo". This function is used by
client.c, which implements an extension module that can be "required"
from Lua.

My first attempt was to use package.loadlib with "*". However, it only
works if I call the loadlib from Lua, as in the works.lua below. When I
tried to put all the magic inside the mylib.c, so it's self-contained,
it did not work (see fails.lua).

So my two questions are:
1) Is this a sane way to export C symbols from a Lua library?
2) Why can't I call package.loadlib("*") from C?

-- Hugo

----------------
-- mylib.c
----------------

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

int mylib_foo(int x) {
   return x + 42;
}

int luaopen_mylib(lua_State *L)
{
   luaL_dostring(L, "assert(package.loadlib('./mylib.so', '*'))");
   return 0;
}

----------------
-- client.c
----------------

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

int mylib_foo(int x);

static
int client_foo(lua_State *L) {
   lua_pushinteger(L, mylib_foo(0));
   return 1;
}

static luaL_Reg exports[] = {
   { "foo", client_foo },
   { NULL, NULL }
};

int luaopen_client(lua_State *L) {
   luaL_newlib(L, exports);
   return 1;
}

----------------
-- build.sh
----------------

gcc -Wall -O2 -fPIC -shared mylib.c -o mylib.so
gcc -Wall -O2 -fPIC -shared client.c -o client.so

----------------
-- fails.lua
----------------

l = require "mylib"
c = require "client" -- error: undefined symbol mylib_foo
print(c.foo())

----------------
-- works.lua
----------------

package.loadlib('./mylib.so', '*')
c = require "client"
print(c.foo())