Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIG_exception() prints SWIG_RuntimeError as string

I wrapped my C++ function using SWIG so I can use it in Lua.

Inside my typemap, I check if the input is table.

if (!lua_istable(L, 1)) {
      SWIG_exception(SWIG_RuntimeError, "argument mismatch: table expected");
    }

But if this is called in Lua, the message prints like the following.

SWIG_RuntimeError:argument mismatch: table expected

I tried to replace SWIG_RuntimeError with -3 but then it just prints -3 instead of SWIG_RuntimeError.

I included the followings

%include <stl.i>
%include <std_string.i>
%include <std_except.i>

%include <exception.i>
%include <typemaps.i>

I tried not including <std_except.i> and/or <exception.i> but none of these fixed the problem.

How can I fix this?

like image 954
Zack Lee Avatar asked Apr 29 '26 20:04

Zack Lee


1 Answers

If you dislike the standard exception handler of SWIG, you simply write your own one. This will, however, not be portable across generators.

This is my interface file:

%module typemaps

%{
#include <vector>
void test_typemap(std::vector<int>) {}
%}

%define lua_exception(msg)
    lua_pushfstring(L, "%s:%d: %s\n", __FILE__, __LINE__, msg);
    SWIG_fail;
%enddef

%typemap(in) std::vector<int> {
    if (!lua_istable(L, 1)) {
        lua_exception("expected table for first argument");
    }
}

void test_typemap(std::vector<int>);

This is the Lua input file:

local typemaps = require("typemaps")
typemaps.test_typemap({1,2,3})
typemaps.test_typemap("not a table")

This is the error message:

lua5.3: test.i:15: expected table for first argument

stack traceback:
    [C]: in function 'typemaps.test_typemap'
    test.lua:3: in main chunk
    [C]: in ?

The first line tells us the point where it went wrong in the interface file. In the stack traceback we then find where it went wrong in the Lua input file, namely at line three (test.lua:3) where we try to call test_typemap with a string. The stack traceback is actually generic to Lua and has nothing to do with SWIG. You'll always get one when you call error.

like image 146
Henri Menke Avatar answered May 01 '26 09:05

Henri Menke