我正在尝试包装一个C++函数,该函数可以接收Lua字符串表,并将其用作C++函数中的字符串数组。
我可以使用浮点类型而不是字符串来成功地完成这个任务。
这是我的功能。
static void readTable(float values[], int len) {
for (int i=0; i<len; ++i)
printf("VALUE : %g", values[i]);
}下面是SWIG接口(.i)文件中的类型映射部分
// using typemaps
%include <typemaps.i>
%apply (float INPUT[], int) {(float values[], int len)};当我在Lua中调用这个函数时,它工作得很好。
但是,如果我将类型更改为std::string而不是float,并将字符串表传递给函数,则在Lua中会出现以下错误。
Error in readTable expected 2..2 args, got 1我不知道这意味着什么,也不知道如何解决这个问题。也许我必须在SWIG接口(.i)文件中添加更多内容?
我很感谢你的帮助。谢谢!
发布于 2018-06-04 04:26:38
typemaps.i文件仅定义基元数值类型的数组的类型映射。
因此,我建议您自己编写类型图。然后还可以使用std::vector<std::string>类型的参数,因此甚至不需要length参数。
%module table_of_strings
%{
#include <iostream>
#include <string>
#include <vector>
void readTable(std::vector<std::string> values) {
for (size_t i=0; i<values.size(); ++i) {
std::cout << "VALUE : " << values[i] << '\n';
}
}
%}
%include "exception.i"
%typemap(in) std::vector<std::string>
{
if (!lua_istable(L,1)) {
SWIG_exception(SWIG_RuntimeError, "argument mismatch: table expected");
}
lua_len(L,1);
size_t len = lua_tointeger(L,-1);
$1.reserve(len);
for (size_t i = 0; i < len; ++i) {
lua_pushinteger(L,i+1);
lua_gettable(L,1);
$1.push_back(lua_tostring(L,-1));
}
}
void readTable(std::vector<std::string> values);swig -c++ -lua test.i
clang++ -Wall -Wextra -Wpedantic -I/usr/include/lua5.3 -fPIC -shared test_wrap.cxx -o table_of_strings.so -llua5.3local tos = require"table_of_strings"
tos.readTable({"ABC", "DEF", "GHI"})VALUE : ABC
VALUE : DEF
VALUE : GHIhttps://stackoverflow.com/questions/50563371
复制相似问题