Home > OS >  Using SWIG to Wrap C Function With Default Values
Using SWIG to Wrap C Function With Default Values

Time:09-23

I have the following C function in say.hpp:

#include <iostream>


void say(const char* text, const uint32_t x = 16, const uint32_t y = 24, const int32_t z = -1) {
    std::cout << text << std::endl;
}

Here is my say.i:

%module say
%{
#include "say.hpp"
%}

%include "say.hpp"

Then, I built the shared library:

$ swig -python -c   -I/usr/include say.i
$ g   -fPIC -c say_wrap.cxx -I/opt/rh/rh-python38/root/usr/include/python3.8 
$ g   -shared say_wrap.o -o _say.so

Then, I tried to call it:

>>> import say
>>> say.say("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/hc/test/cpp/say.py", line 66, in say
    return _say.say(text, x, y, z)
TypeError: Wrong number or type of arguments for overloaded function 'say'.
  Possible C/C   prototypes are:
    say(char const *,uint32_t const,uint32_t const,int32_t const)
    say(char const *,uint32_t const,uint32_t const)
    say(char const *,uint32_t const)
    say(char const *)

>>> 

It seems something is wrong with having default values for the function parameters as once I remove them, it works.

Any idea?

CodePudding user response:

Use the following say.i file. SWIG has prewritten code for the standard integer types and needs it included to understand them. Without them, the wrapper receives the default values as opaque Python objects and doesn't know how to convert them to the correct C integer types.

%module say
%{
#include "say.hpp"
%}
%include <stdint.i>
%include "say.hpp"

Result:

>>> import say
>>> say.say('hello')
hello
>>> say.say('hello',1,2,3)
hello

Note you could also supply the typedefs directly, but better to use stdint.i:

%module say
%{
#include "say.hpp"
%}
typedef unsigned int uint32_t;
typedef int int32_t;
%include "say.hpp"
  • Related