Sunday, December 21, 2008

How I have created a python module from a C++ lib with swig

Today, I have completed the first step to create a python module from my C++ library. The first function I want to call from flayers is the main wrapper (fexp.cpp:main(int argc, char** argv)). From the new flayers python module, I expect to be able to call it that way :

import flayers
flayers.fexp(["fexp","/","-e","10","-h","100","--oh","--lsm","-l","0.01"])


Unfortunately, it is a little bit more complicated then expected. In order to make it working, I have looked at this great documentation (doc). Here are a summary of issues I have encounter.
1) Extension module doesn't work automatically with C++. You have to add "-c++" option to swig call (ex: swig -python -c++ flayers.i).
2) I added the .cxx file generated from swig instead of .i file to the source file in the setup extension instance (variant from my previous blog post).
3) I have added flayers dependancy classes to the extension sources to ensure I didn't get error like : ImportError: ./_flayers.so: undefined symbol: XXXX and ensure the lib is recompiled at the installation.
4) How to pass the list of options without argc and not get error like "in method 'fexp', argument 2 of type 'char **'": see section "30.9.2 Expanding a Python object into multiple arguments" ? look at my setup.py

You can take a look at my files here (flayers.i, setup.py, flayers.h,flayers.cpp)
I am impress, swig and python are just allsum.

If you want to try it, download flayers and do:
svn co https://mlboost.svn.sourceforge.net/svnroot/mlboost/flayers flayers
cd flayers
python setup.py build_ext --inplace (or python setup.py install)
ipython (or python)
import flayers
flayers.fexp(["fexp","/","-e","10","-h","100","--oh","--lsm","-l","0.01"])

No comments:

Post a Comment