包装C++函数以使用 SWIG 获取 Lua 字符串表
Wrapping C++ function to take Lua table of strings using SWIG
我正在尝试包装一个可以接收Lua字符串表并将其用作C++函数中的字符串数组的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( 文件添加更多内容?
我将不胜感激任何帮助。谢谢!
typemaps.i
文件仅定义基元数值类型数组的类型图。
因此,我建议您编写自己的类型图。 然后你也可以取一个类型std::vector<std::string>
的参数,所以你甚至不需要长度参数。
%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.3
local tos = require"table_of_strings"
tos.readTable({"ABC", "DEF", "GHI"})
VALUE : ABC
VALUE : DEF
VALUE : GHI
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在C++中获取lua函数作为参数,然后调用它
- 如何在C++中从Lua函数获取返回表?
- 如何获取从C++发送到Lua函数的表的更新值?
- 包装C++函数以使用 SWIG 获取 Lua 字符串表
- 使用 liblua 获取 Lua 语法树
- C++-Lua:获取调用方表名
- luabind获取c++对象的类元表,将obj作为参数推送到lua函数
- Lua:加载第二个字符串后无法获取字段;
- Lua C API - 从堆栈上的表中获取元表
- 如何从Lua运行过程中读取变量值(获取过程变量值)
- 如何使用 gdb 从核心文件中获取 lua 堆栈跟踪
- 如何从lua文件到c++获取字符串
- Lua:加载文件后获取全局函数失败
- Lua & C++ API 获取执行信息
- Lua从参数中获取函数