包装C++函数以使用 SWIG 获取 Lua 字符串表

Wrapping C++ function to take Lua table of strings using SWIG

本文关键字:获取 Lua 字符串 SWIG C++ 函数 包装      更新时间:2023-10-16

我正在尝试包装一个可以接收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