C++调用lua_dostring加载包含'require('cjson')'的lua脚本会出错:cjson.so:未定义的符号:lua_getfield

我在Lua脚本中定义了一个函数,并从我的C++程序中调用它。Lua脚本使用cjson模块。我可以通过Lua二进制文件执行Lua脚本,但它无法在我的C++程序中运行。 错误信息:

从文件'/usr/local/app/cswuyg/test_lua/install/cjson.so'加载模块'cjson'时出错: /usr/local/app/cswuyg/test_lua/install/cjson.so:未定义的符号:lua_getfield

cpp代码:

    extern "C"
{
    #include "lua.h"
    #include "lualib.h"
    #include "lauxlib.h"
}
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

void test_dostring(lua_State* L, const std::string& file_path) {
    std::ifstream ifs;
    ifs.open(file_path.c_str());
    if (!ifs.is_open()) {
        return ;
    }
    std::stringstream buffer;
    buffer << ifs.rdbuf();
    std::string file_info(buffer.str());
    // 测试luaL_dostring
    std::cout << luaL_dostring(L, file_info.c_str()) << std::endl;
    std::cout << "错误信息:" << lua_tostring(L, -1) << std::endl;
    lua_getglobal(L, "comment2");
    lua_pushstring(L, "xxx");
    lua_call(L, 1, 0);
    std::string lua_ret = lua_tostring(L, -1);
    std::cout << "返回值:" << lua_ret << std::endl;
}

int main(int argc, char* argv[]) {
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);
    test_dostring(L, "test.lua");
    lua_close(L);
    return 0;
}

Lua代码:

local Json = require('cjson')
function comment2(test)
    print(test)
end
comment2("xx")

如何解决?感激不尽。

点赞
用户107090
用户107090

如果你正在使用 Linux 并且 Lua 核心库已经静态链接到你的程序中,你需要在构建程序时使用 -Wl,-E 来暴露 Lua C API。这是从 lua.org 构建 Lua 命令行解释器所使用的咒语。

2017-06-09 15:52:06