SWIG %insert directive
It is often convenient to insert some verbatim code into SWIG generated wrappers to go along with all of the automatically generated code. For this purpose SWIG has the %insert directive, which takes a parameter which is the section to insert the code into, e.g.:
%insert("header") %{ #include <myheader.h> %}
which adds an include of myheader.h to the the top of the C-wrapper file. Besides the "header" section, code can be inserted into other parts of the generated code.
Very usefully, verbatim code can also be inserted into the part of the wrapper that is in the target language. The simple example is for Python wrapper which has a shortcut %pythoncode which in fact stands for %insert("python") and inserts into the Python part of the wrappers. Other languages have similar facilities: for example, for "R"-language targets, you can insert code by using %insert("sclasses") to insert verbatim R code into R parts of the wrapper.
The way to see comprehensive list of sections which are available to insert into is to look for ''Swig_register_filebyname'' lines in the SWIG source file for the target language. For example, in r.cxx you can find:
Swig_register_filebyname("sinit", s_init); Swig_register_filebyname("sinitroutine", s_init_routine); Swig_register_filebyname("begin", f_begin); Swig_register_filebyname("runtime", f_runtime); Swig_register_filebyname("init", f_init); Swig_register_filebyname("header", s_header); Swig_register_filebyname("wrapper", f_wrapper); Swig_register_filebyname("s", sfile); Swig_register_filebyname("sclasses", s_classes);
The available sections are then sinit, sinitroutine, begin, runtie, init, header, wrapper, s and sclasses.