Home > database >  How can SWIG read a C defined value if the type is explicitly stated?
How can SWIG read a C defined value if the type is explicitly stated?

Time:08-24

I am using SWIG (4.0.1) to generate Python modules from my C header files. SWIG processes the following define properly into the python module:

#define SWIG_TEST_DEFINE 3

(It will look like this in the generated python module my_interface.py):

SWIG_TEST_DEFINE = _my_interface.SWIG_TEST_DEFINE

but will not accept (and add to the generated python module):

#define SWIG_TEST_DEFINE ((int)3)

I am looking for a solution to make SWIG also process these constructs where a type is specified.

CodePudding user response:

I think it is because int is not a valid type in Python, try using the Py_BuildValue method as that converts a C type to a Python one. That might be why, however if that's the case I don't know why it just accepts 3.

I would add this as a comment but cannot due to lack of reputation.

CodePudding user response:

If you're willing to change the header, you can do the following so SWIG will define the variable as 3 but the macro will still correct for C:

#ifdef SWIG
#define SWIG_TEST_DEFINE 3
#else
#   define SWIG_TEST_DEFINE ((int)3)
#endif

If not willing to change the header, you can include it normally, then redefine the macro just for SWIG. Below assumes test.h contains #define SWIG_TEST_DEFINE ((int)3):

%module test

%{
#include "test.h"
%}

%include "test.h"
#undef SWIG_TEST_DEFINE
#define SWIG_TEST_DEFINE 3
  • Related