Preprocessor macro in SWIG

I am trying to get SWIG to recognize a simple macro processor that "defines" a new function based on a different definition and more complex function. So, in the C header file, I have:

#define FOO 1 #define my_macro_fun(args) my_fun(args,FOO) 

SWIG sees and successfully wraps my_fun , but I want it to my_macro_fun .

+4
source share
1 answer

SWIG is trying to identify macros that are constants and wrap them, but it cannot do anything smart with such a macro. Fortunately, it’s easy to work there. Imagine you have the following header file:

 #define FOO 1 #define my_macro_fun(args) my_fun(args,FOO) void my_fun(int a, int b); 

You can wrap it like this:

 %module test %{ #include "test.h" %} %include "test.h" 

which skips the my_macro_fun function. To get SWIG to wrap this, all you have to do is:

 %module test %{ #include "test.h" %} // Lie! Tell SWIG that it should be wrapped like any other function. void my_macro_fun(int); // This is entirely optional: it will cause my_fun to be wrapped as well %include "test.h" 

This little lie is fine in SWIG - it will generate Wrapper code that assumes that my_macro_fun(int) can be called, just as if you were using a macro. When compiling the wrapper, the compiler will end using the macro there, and no one will be wiser.

Please note that order is important - a function that really needs to be executed by the macro before %include in the interface file, otherwise SWIG will try to expand the macro while parsing your declaration, which will lead to a syntax error. You can skip %include or use %ignore if you want to enable it for other parts, but suppress the original my_fun in the generated interface.


With some SWIG languages ​​(e.g. Python), you can also use the default sample map :

 %module test %{ #include "test.h" %} %typemap(default) int b { $1 = FOO; } %include "test.h" 

To specify a value for an argument if no value is specified for it.

+4
source

All Articles