Alex
Alex

Reputation: 3381

How call function in lua library with dlsym

I am trying call a lua library runtime, so I made a lua lib in C

static int my_new(lua_State *L) {
  printf("test_new");
}

LUALIB_API int luaopen_my(lua_State *L) {
  static const luaL_Reg R[] =
  {
  { "new",                        my_new },
  { NULL,                         NULL }
  };

  luaL_newmetatable(L,myNAME);
  luaL_setfuncs(L,R,0);
  lua_pushliteral(L,"version");                  /** version */
  lua_pushliteral(L,MYVERSION);
  lua_settable(L,-3);
  lua_pushliteral(L,"__index");
  lua_pushvalue(L,-2);
  lua_settable(L,-3);
  return 1;
}

So I built it as a dynamic library, and I tried call doing it:

void *handle;
lua_CFunction fnc_call;

handle = dlopen("mylib.so", RTLD_LOCAL | RTLD_LAZY);
if (!handle) {
  printf("error call lib");
  exit(-1);
}

fnc_call = (lua_CFunction) dlsym(handle, "luaopen_my");
if (fnc_call == NULL)  {
  printf("error call func");
  exit(-1);
}

luaL_requiref(L, "my", fnc_call, 1);
lua_pop(L, 1);

But when I call the Lua code that uses that I have a segmentation fault.

test = my.new()

How should I call a lib lua in my program, I know that is possible put my lib in some lua path and lua api call my libs, but I need to call it using dlopen.

Thanks,

Upvotes: 1

Views: 380

Answers (1)

Oliver
Oliver

Reputation: 29463

I wager that since you are not returning a value from my_new, the function is returning a random value which tells Lua that there is some (random, possibly very high) number of objects returned on the stack. Since this is not true, when Lua clears that stack from return values it removes objects from the stack although none were added, likely removing more objects than there are on the stack, thus corrupting memory.

Add return 0 to my_new.

Upvotes: 2

Related Questions