Tuesday, December 14, 2010

SWIG and fstream

I have a love/hate relationship with swig.
I have had some success wrapping C and C++ libraries so they can be called from python. The real plus with swig is that is not invasive to existing code, with a little work you can usually create good wrappers without having to change underlying code.
However, when it fails it can be hard to spot why. I've found that looking at the C++ wrapper code that swig produces can help a lot, but still there can be a lot of thrashing around.
My latest battle was with fstream. I had a method that need a C++ stream to read from and I wanted to open a specific file, so I needed fstream. Unfortunately, I had no joy wrapping the fstream header file. Some googling suggested that C++ streams are one area where swig struggles.
In the end, my solution was to just create a function that takes a filename and returns an istream:
%inline %{
istream & open_stream(const char *filename) {
istream *infile = new ifstream(filename);
return *infile;
istream & open_stream(const char *filename);
Armed with this I can open files and get the istream objects I need to pass into methods that read streams.
I'd be interested to hear of any better solutions.

No comments: