c++luaswigtypemaps

Simpler way to create a SWIG typemap for a function with multiple arguments?


Here's the C++ function that I want to wrap using SWIG.

static void my_func(t_string name, t_string value)
{
    do_something(name, value);
}

And here are the SWIG typemaps.

%typemap(in) (t_string name)
{
    if (!lua_isstring(L, $input)) {
      SWIG_exception(SWIG_RuntimeError, "argument mismatch: string expected");
    }
    $1 = lua_tostring(L, $input);
}

%typemap(in) (t_string value)
{
    if (!lua_isstring(L, $input)) {
      SWIG_exception(SWIG_RuntimeError, "argument mismatch: string expected");
    }
    $1 = lua_tostring(L, $input);
}

This way, I could successfully use my_func in Lua.

But I wonder if there's any simpler solution than this since the above 2 typemaps are identical but only use different name.

Let's say if I later have a C++ function that takes 3 t_string arguments, then should I add one more typemap using different name? Or would there be any simpler solution?


Solution

  • You're doing it wrong. You are using a multi-argument typemap for a single type. Remove the variable name (and optionally the parentheses) from t_string. This is explained in details in the section about pattern matching in the chapter for typemaps of the documentation.

    %module typemaptest
    
    %typemap(in) t_string
    {
        if (!lua_isstring(L, $input)) {
          SWIG_exception(SWIG_RuntimeError, "argument mismatch: string expected");
        }
        $1 = lua_tostring(L, $input);
    }
    
    void my_func(t_string name, t_string value);