我正在测试lua(5.1)中的c / c ++模块。没有向量的情况下,代码运行良好。但是当我包含stl / vector并在Function add中声明一个向量变量时,该程序会导致分段错误。
libvec.so代码:
#include <vector>
#include <list>
#include "lua.hpp"
#include <algorithm>
#include <iostream>
#include <string>
#include <map>
extern "C" int add(lua_State* L)
{
double op1 = luaL_checknumber(L, 1);
double op2 = luaL_checknumber(L, 2);
//std::vector<double> vec;
//vec.push_back(op1);
//vec.push_back(op2);
//lua_pushnumber(L, vec[0]+vec[1]);
lua_pushnumber(L, op1 + op2);
return 1;
}
static luaL_Reg mylibs[] = {
{"add", add}
};
extern "C" int luaopen_libvec(lua_State *L){
luaL_register(L, "libvec", mylibs);
return 1;
}
test.lua代码:
local vec = require 'libvec'
print(vec.add(1,212))
然后我尝试gdb lua /运行test.lua,然后获取
strlen () at ../sysdeps/x86_64/strlen.S:106
106 ../sysdeps/x86_64/strlen.S: No such file or directory.
(gdb) bt
#0 strlen () at ../sysdeps/x86_64/strlen.S:106
#1 0x000000000040596e in lua_setfield ()
#2 0x0000000000412f75 in luaL_openlib ()
#3 0x00007ffff6e8e531 in luaopen_libvec () from ./libvec.so
#4 0x00000000004080d8 in luaD_precall ()
#5 0x00000000004084e4 in luaD_call ()
#6 0x0000000000405c95 in lua_call ()
#7 0x000000000041dcaa in ll_require ()
#8 0x00000000004080d8 in luaD_precall ()
#9 0x00000000004116d2 in luaV_execute ()
#10 0x000000000040852d in luaD_call ()
#11 0x000000000040782b in luaD_rawrunprotected ()
#12 0x000000000040868b in luaD_pcall ()
#13 0x0000000000405d26 in lua_pcall ()
#14 0x0000000000403ecc in docall ()
#15 0x00000000004048a9 in pmain ()
#16 0x00000000004080d8 in luaD_precall ()
#17 0x00000000004084e4 in luaD_call ()
#18 0x000000000040782b in luaD_rawrunprotected ()
#19 0x000000000040868b in luaD_pcall ()
#20 0x0000000000405db5 in lua_cpcall ()
#21 0x0000000000403b94 in main ()
我有测试声明std :: map,并且在std :: string正常工作时也崩溃了...
答案 0 :(得分:2)
摘自luaL_register
的文档:
任何luaL_Reg数组都必须以哨兵条目结尾,其中name和func均为NULL。
情况并非如此,我可以想象添加std::vector
方法来搁置以前碰巧存在的一些空字节。
tl; dr:向{NULL, NULL}
添加一个myLibs
条目。
答案 1 :(得分:2)
摘自文档https://www.lua.org/manual/5.1/manual.html#luaL_ref:
要由luaL_register注册的功能数组的类型。 name是函数名称,func是指向函数的指针。 luaL_Reg的任何数组都必须以哨兵条目结尾,其中name和func均为NULL。
luaL_register在数组上进行迭代,直到找到前哨值为止,因为它找不到在数组末尾读取的值。
正确的数组是:
static luaL_Reg mylibs[] = {
{"add", add},
{NULL, NULL}
};