无法使用Lua的C ++模块

时间:2019-07-31 09:52:14

标签: c++ lua

我正在尝试使用lua用C ++编写的函数。下面是cpp文件:

extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}

static int  add_5(lua_State *L)
{
  double d = lua_tonumber(L, 1); /* get argument */
  d=d+5;
  lua_pushnumber(L, d); /* push result */
  return 1; /* number of results */
}

static const struct luaL_Reg mylib [] =
{
  {"add_5", add_5},
  {NULL, NULL} /* sentinel */
};

int luaopen_mylib (lua_State *L)
{
  //luaL_newlib(L, mylib); //This is not working.
  luaL_register(L, NULL, mylib);
  return 1;
}

我使用以下命令通过g ++编译了以上代码:

g++ -shared -o mylib.so test.cpp -fPIC

我在lua解释器上遇到以下错误:

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> local temp = require "mylib"
error loading module 'mylib' from file './mylib.so':
        ./mylib.so: undefined symbol: luaopen_mylib
stack traceback:
        [C]: ?
        [C]: in function 'require'
        stdin:1: in main chunk
        [C]: ?

编辑1 :根据suggested link,我将luaopen_mylib函数包含在extern“ C”块内。我之前遇到的错误现在已由新错误替换。现在我得到了:

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> local temp = require "mylib"
attempt to index a string value
stack traceback:
        [C]: ?
        [C]: in function 'require'
        stdin:1: in main chunk
        [C]: ?

编辑2 :我在'Attempt to index a string value' error while loading a c++ module in lua上添加了一个新问题

0 个答案:

没有答案