I try to create a python interface to c++ code using SWIG. I'm using Ubuntu 16.04, the anaconda distribution of python 3.6 and SWIG version 3.0.8 This repository containts all files needed to build and test the examples. The .gitignore containts all files that are generated by the commands discussed below.
Interesting reference link for numpy: numpy.i swig interface.
I first tried the example from the SWIG-website.
swig -python example.i
gcc -fPIC -c example.c example_wrap.c -I /home/jeroen/anaconda3/include/python3.6m
ld -shared example.o example_wrap.o -o _example.so
I use the option -fPIC
because this was suggested by the following error when building the shared library:
relocation R_X86_64_32S against '.rodata' can not be used when making a shared object; recompile with -fPIC example_wrap.o: error adding symbols: Bad value
This is all working as expected, including my custom c function:
swig -python prime.i
gcc -fPIC -c prime.c prime_wrap.c -I /home/jeroen/anaconda3/include/python3.6m
ld -shared prime.o prime_wrap.o -o _prime.so
Now it begins...
swig -c++ -python prime.i
g++ -fPIC -c prime.cxx prime_wrap.cxx -I /home/jeroen/anaconda3/include/python3.6m
g++ -shared prime.o prime_wrap.o -o _prime.so
It works! Strange. It seems that it now creates a prime.py file, which it dit not in earlier tests. Also notice that you use g++ instead of ld to build shared c++ libraries.