问题描述
我最近使用5.2进行学习,我想这样尝试:
I use 5.2 for learning recently, what I want to try like this:
第1步,为lua构建一个c模块:
Step 1, build a c module for lua:
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include <stdlib.h>
static int add(lua_State *L) {
int x = luaL_checkint(L, -2);
int y = luaL_checkint(L, -1);
lua_pushinteger(L, x + y);
return 1;
}
static const struct luaL_Reg reg_lib[] = {
{"add", add}
};
int luaopen_tool(lua_State *L) {
luaL_newlib(L, reg_lib);
lua_setglobal(L, "tool");
return 0;
}
我编译并将其与liblua.a链接,并且我确定它可以在lua脚本(例如"require("tool")tool.add(1、2))中正常工作
I compile and link it with liblua.a, and I'm sure it works well in lua script like "require("tool") tool.add(1, 2)"
第2步,我编写了另一个C程序,该程序想要在第1步中使用我的c模块,如下所示:
Step 2, I write another C program that wants to require my c module in step 1 like this:
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include <stdlib.h>
int main(int argc, char* const argv[]) {
lua_State *L = luaL_newstate();
luaL_requiref(L, "base", luaopen_base, 1);
luaL_requiref(L, "package", luaopen_package, 1);
lua_getglobal(L, "require");
if (!lua_isfunction(L, -1)) {
printf("require not found\n");
return 2;
}
lua_pushstring(L, "tool");
if (lua_pcall(L, 1, 1, 0) != LUA_OK) {
printf("require_fail=%s\n", lua_tostring(L, -1));
return 3;
}
lua_getfield(L, -1, "add");
lua_pushinteger(L, 2);
lua_pushinteger(L, 3);
lua_pcall(L, 2, 1, 0);
int n = luaL_checkint(L, -1);
printf("n=%d\n", n);
return 0;
}
我还编译&与liblua.a链接,但是在运行它时发生错误:"require_fail =检测到多个Lua虚拟机"
I also compile & link with liblua.a, but error occurs when I run it:"require_fail=multiple Lua VMs detected"
有人的博客说,在lua5.2中,您应该动态地而不是静态地链接c模块和c主机程序.
Someone's blog said that in lua5.2, you should link c module and c host program both dynamicly, but not staticly.
有人遇到同样的问题,还是我的代码出了点问题,谢谢.
is there someone that has the same problem, or is there somehing wrong in my code, thanks.
注意:
使用-Wl,-E编译主程序已解决了问题,非常感谢您的所有帮助^^.
the problem has been solved by compile main program with -Wl,-E, thanks a lot for all your help ^^.
推荐答案
从中创建.so时,请勿将C模块与liblua.a链接.有关示例,请参见我的Lua库页面: http://www.tecgraf .puc-rio.br/〜lhf/ftp/lua/.您可以将liblua.a静态链接到主程序,但是必须在链接时添加-Wl,-E
来导出其符号.这就是在Linux中构建Lua解释器的方式.
Don't link your C module with liblua.a when you create a .so from it. For examples, see my page of Lua libraries: http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/ . You can link liblua.a statically into your main program but you have to export its symbols by adding -Wl,-E
at link time. That's how the Lua interpreter is built in Linux.
这篇关于lua5.2的错误:检测到多个Lua虚拟机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!