我正在尝试创建一个getter函数,该函数在Lua中返回一个成对向量。
我在C ++中具有以下矢量数据:
{{1, "a"}, {2, "b"}, {3, "c"}}
我想将此向量作为Lua中的表返回,因此它可以与Lua中的下表t
相同:
local t = {};
t[1].value = 1
t[1].name = "a"
t[2].value = 2
t[2].name = "b"
t[3].value = 3
t[3].name = "c"
这是我的代码:
MyBindings.h
” #include "main.h"
class MyClass
{
public:
MyClass()
:MyData({{1, "a"}, {2, "b"}, {3, "c"}}){}
void getMyData(std::vector<pair<float, std::string>> *datap)
{
*datap = MyData;
}
std::vector<pair<float, std::string>> MyData;
};
MyBindings.i
” %module my
%{
#include "MyBindings.h"
%}
%include <stl.i>
%include <typemaps.i>
%include <std_string.i>
%include <std_vector.i>
/* convert the output std::vector<pair<float, std::string>> to lua_Table */
%typemap(in, numinputs = 0) (std::vector<pair<float, std::string>> *datap)
(std::vector<pair<float, std::string>> *tdatap = nullptr)
%{
%}
%typemap(argout) (std::vector<pair<float, std::string>> *datap)
{
lua_newtable(L);
for (size_t i = 0; i < $1->size(); ++i)
{
lua_newtable(L);
lua_pushinteger(L, static_cast<lua_Number>($1->at(i).first));
lua_setfield(L, -2, "value");
lua_pushstring(L, $1->at(i).second.c_str());
lua_setfield(L, -2, "name");
lua_rawseti(L, -2, i + 1);
}
SWIG_arg++;
}
%include "MyBindings.h"
main.cpp
” #include "main.h"
#include "lua.hpp"
extern "C"
{
int luaopen_my(lua_State *L);
}
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaopen_my(L);
lua_settop(L, 0);
luaL_dostring(L, "local c = my.MyClass()\n"
"local t = c:getMyData()\n"
"print('Value : ' .. t[2].value)\n"
"print('Name : ' .. t[2].name)\n");
lua_close(L);
}
Value : 2
Name : b
vector:线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x10)
如何更改代码以获得所需的结果?
答案 0 :(得分:1)
基本上,解决方案是不使用输出参数(argout
)。这实际上是C ++编程的一般建议。当您无法轻松地从函数中按值返回数组时,在C时代需要输出参数。
经过一些重构后,我得到以下结果:
MyBindings.h
#include <string>
#include <utility>
#include <vector>
class MyClass {
std::vector<std::pair<float, std::string>> m_data;
public:
MyClass() : m_data({{1, "a"}, {2, "b"}, {3, "c"}}) {}
std::vector<std::pair<float, std::string>> data() { return m_data; }
};
MyBindings.i
%module my
%{
#include "MyBindings.h"
%}
%typemap(out) std::vector<std::pair<float, std::string>>
{
lua_newtable(L);
for (size_t i = 0; i < $1.size(); ++i)
{
lua_newtable(L);
lua_pushinteger(L, static_cast<lua_Number>($1.at(i).first));
lua_setfield(L, -2, "value");
lua_pushstring(L, $1.at(i).second.c_str());
lua_setfield(L, -2, "name");
lua_rawseti(L, -2, i + 1);
}
SWIG_arg++;
}
%include "MyBindings.h"
main.cpp
#include "lua.hpp"
extern "C"
{
int luaopen_my(lua_State *L);
}
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaopen_my(L);
lua_settop(L, 0);
luaL_dostring(L, "local c = my.MyClass()\n"
"local t = c:data()\n"
"print('Value : ' .. t[2].value)\n"
"print('Name : ' .. t[2].name)\n");
lua_close(L);
}
示例调用:
$ swig -c++ -lua MyBindings.i
$ clang++ -Wall -Wextra -Wpedantic -std=c++11 -I/usr/include/lua5.3 MyBindings_wrap.cxx main.cpp -llua5.3
$ ./a.out
Value : 2
Name : b