Peter Toft
Peter Toft

Reputation: 707

Wrap C++ to Python - where parts of the code is a shared library without source

I have a Linux .so-library secdyn.so with a headerfile without source.

/* secdyn.h */
int sec2(int a);

I want to wrap this to Python via Swig, thus I write a subdyn.h

#include <iostream>
#include "secdyn.h"
int subdyn(int a,int debuglevel);

and a subdyn.cpp

#include "subdyn.h"
int subdyn(int a,int debuglevel)
{
  if (debuglevel>0) std::cout << "a = " << a << std::endl;
  return sec2(a);
}

and a subdyn.i (see below in my answer!!! - error in this first line)

%module substatic
%{ 
  #define SWIG_FILE_WITH_INIT
  #include "subdyn.h"
%}
%include "subdyn.h"

and compile with

swig -c++ -python subdyn.i
g++ -fPIC subdyn_wrap.cxx -c -g -I/usr/include/python2.7/
g++ -fPIC subdyn.cpp -c -g
g++ -shared subdyn_wrap.o subdyn.o secdyn.so -o _subdyn.so 

This builds and I set $LD_LIBRARY_PATH to include "pwd"

$ ldd _subdyn.so
linux-gate.so.1 =>  (0xb7702000)
secdyn.so => ./secdyn.so (0xb76f4000)
libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0xb75ee000)
libm.so.6 => /lib/i386-linux-gnu/i686/cmov/libm.so.6 (0xb75c7000)
libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0xb75aa000)
libc.so.6 => /lib/i386-linux-gnu/i686/cmov/libc.so.6 (0xb7446000)
/lib/ld-linux.so.2 (0xb7703000)

I can make a C++ binary that uses secdyn.so and subdyn.so - that works fine.

However I cannot import this library to Python

$ python
>>> import subdyn
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define init function (initsubdyn)

I can note that everything works fine if the secdyn comes as a static libary, but for a dynamic library this breaks.

I have attached a static swig link exampe that works, and a dynamic link example (the code above) which does not work at http://petertoft.dk/code/swig.tgz

Clues?

Upvotes: 2

Views: 145

Answers (1)

Peter Toft
Peter Toft

Reputation: 707

The bug I missed above is the subdyn.i which was wrong. The first line should read %module subdyn

Then it works. I have re-uploaded http://petertoft.dk/code/swig.tgz - which contains a static and a dynamic example. Both work now :)

Upvotes: 2

Related Questions