我正在 lua(5.1) 中测试调用 c/c++ 模块。如果没有 vector ,代码运行良好。但是当我包含 STL/vector 并在函数 add 中声明一个 vector 变量时,程序会导致段错误。
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 运行良好......
最佳答案
来自luaL_register
的文档:
Any array of luaL_Reg must end with an sentinel entry in which both name and func are NULL.
这里不是这种情况,我可以想象添加 std::vector
方法来推开一些以前恰好存在的空字节。
tl;dr:将 {NULL, NULL}
条目添加到 myLibs
。
关于c++ - 在 C 模块中声明一个 vector 变量导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51610738/