C++调用lua_dostring来加载具有"require('cjson')"的Lua Scrip引发错误:cjson.so:未定义的符号:lua_getfield



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

从文件"/usr/local/app/cswuyg/test_lua/install/cjson.so"加载模块"cjson"时出错: /usr/local/app/cswuyg/test_lua/install/cjson.so: undefined symbol: 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());
    // test luaL_dostring
    std::cout << luaL_dostring(L, file_info.c_str()) << std::endl;
    std::cout << "error msg:" << 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 << "ret:" << 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")

如何解决? 任何帮助将不胜感激。

如果您使用的是 Linux,并且 Lua 核心库静态链接到您的程序中,则需要在构建程序时使用 -Wl,-E 公开 Lua C API。这是用于从 lua.org 构建Lua命令行解释器的咒语。

最新更新