Search code examples
swig

Why this redundancy in Swig interface file?


I see here that the swig interface file has identical declarations at 2 places (in and after %{ }% part).

/* example.i */
 %module example
 %{
 /* Put header files here or function declarations like below */
 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();
 %}
 
 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();

Why is this redundancy needed?


Solution

  • The code between %{ and %} is directly injected in the generated SWIG wrapper code to make the declarations available to the compiler. For example you could have a utility function in this block that's only visible to the compiler but not exposed to the target language, or add #include statements needed to compile the wrapper.

    Code outside that block is parsed by SWIG and exposed to the target language. If you left out one of the declarations in this section it wouldn't be exposed to the target language.

    You can eliminate the redundancy in this case by using %inline, which both injects the code into the wrapper and parses it for exposure to the target language:

    %module example
    
    %inline %{
    extern double My_variable;
    extern int fact(int n);
    extern int my_mod(int x, int y);
    extern char *get_time();
    %}