在 Lua 中无法使用 C++ 模块

我正在尝试从 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); /* 获取参数 */
  d=d+5;
  lua_pushnumber(L, d); /* 推入结果 */
  return 1; /* 结果数 */
}

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

int luaopen_mylib (lua_State *L)
{
  //luaL_newlib(L, mylib); // 这无效。
  luaL_register(L, NULL, mylib);
  return 1;
}

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

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

在 lua 解释器中出现了以下错误:

Lua 5.1.4  版权所有©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:根据建议的链接,我已经将 luaopen_mylib 函数封装在 extern "C" 块中。我之前遇到的错误已被新错误所取代。现在我得到了这个:

Lua 5.1.4  版权所有©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:我添加了一个新的问题 @ '在加载 lua 中的 c++ 模块时出现'attempt to index a string value' 错误

点赞