使用 SWIG 将 C++ 函数接收 Lua 字符串表

我想要封装一个 C++ 函数,它可以接收 Lua 字符串表,并将其作为 C++ 函数的字符串数组使用。

我已经成功地使用 float 类型来代替字符串来完成这个功能。

下面是我的函数。

static void readTable(float values[], int len) {

        for (int i=0; i<len; ++i)
            printf("VALUE : %g", values[i]);
    }

下面是 SWIG 接口文件 (.i) 中的 typemaps 部分。

// 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) 中添加更多的内容?

我将非常感谢任何帮助。谢谢!

点赞
用户1944004
用户1944004

文件 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,“参数不匹配:需要表格”);
    }

    lua_len(L,1);
    size_t len = lua_tointeger(L,-1);

    $1.reserve(len);

    forsize_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
2018-06-04 04:26:38