In order to be able to access the C++ code from Python (or other languages) I have wrapped some of the functionality using SWIG (Simple Wrapper Interface Generator). There is a short tutorial on this page which covers some of the basics, however this is not enough. I am going to want to wrap far more complex data types and classes.
Getting startedStarting with some code
/ File : example.c
* Created by Glen Berseth
* Date: Oct 25, 2015
int my_mod(int x, int y)
char * get_time()
Created on: 2015-10-25
virtual void updateWord(std::string word);
virtual std::string getWord();
#endif / WORD_H_ /
There are some global methods, some global variables and a class that uses a non C-like class std::string.
Created on: 2015-10-25
Word::Word(std::string the_word) :
// TODO Auto-generated constructor stub
// TODO Auto-generated destructor stub
void Word::updateWord(std::string word)
this->_the_word = word;
Create an Interface File
An interface file is kind of like a header file but to be used specifically by swig. In the file you should include all of the methods/attributes/variables/header file you want to be exported. For example:
Note: to be able to use std::string properly you need to include the interface file for the class (std_string.i).
/ example.i /
/ Put header files here or function declarations like below /
This interface file includes both the header files for the methods and class(es) I want to be able to use in Python.
Generating and Compiling
I found this part to be the most confusing and difficult. SWIG can generate a enormous wrapper file that is almost unreadable and then you need to compile it. The errors you get from this process may not seem simple.
- First generate the wrapper code
swig3.0 -c++ -python example.i
Note: The -c++ help because it tells SWIG what language is being wrapped, I think it might be C be default.
- Compile the code
g++ -fpic -c example.h example_wrap.cxx Word.cpp -I/usr/include/python2.7/
You need to add the include directory to that the compilation can find "Python.h".
- Link and Build
gcc -shared example_wrap.o Word.o -o _example.so -lstdc++
Use in Python
Using the library in python not might needs be so straightforward. In a more customary Python manner the first argument to a class method is the class object itself. This method is done manually in when using the generated Python code.
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import _example
>>> w = _example.new_Word("meat")