简体   繁体   中英

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

I'm trying to wrap a C++ function that can receive Lua table of strings and use it as an array of strings in C++ function.

I could successfully do this using float type instead of string.

Here's my function.

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

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

And here's the typemaps part from SWIG interface (.i) file

// using typemaps
%include <typemaps.i>
%apply (float INPUT[], int) {(float values[], int len)};

It works fine when I call this function in Lua.

However, if I change the type to std::string instead of float and pass table of strings to the function, I get the following error in Lua.

Error in readTable expected 2..2 args, got 1

I don't know what this means and how to fix this. Maybe I have to add something more to the SWIG interface (.i) file?

I would appreciate any help. Thanks!

The typemaps.i file only defines typemaps for arrays of the primitive numeric types .

Thus I recommend that you write your own typemap. Then you can also take an argument of type std::vector<std::string> , so you don't even need the length parameter.

%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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM