C Function Pointer Wrapping Example not working

Nick Craig-Wood nick at craig-wood.com
Mon Nov 17 15:29:57 EST 2008


Charlie <Charlie.Xia.FDU at gmail.com> wrote:
> 
> >
> > > ?But when I try to import test in python, it complains:
> > > ?import _test
> > > ?ImportError: ./_test.so undefined symbol: _Z9binary_opiiPFiiiE
> >
> > The above is a mangled name so you've got some C vs C++ problems I'd
> > say.
> >
> > You could try putting some extern "C" {} in around all the functions
> > which are imported and exported. ?Have a look at the code SWIG
> > generates and see if it puts some extern "C" in and match what it
> > does in your code.
> >
> > We used to use SWIG in for python embedding in our C++ project, but we
> > found that using ctypes is a lot easier. ?You just write C .so/.dll
> > and use ctypes to access them. ?You can do callbacks and embedding
> > python like this too.
> 
>  Thanks Nick.
> 
>  I tried your method, if I am right(please see the attached details),
>  and I still got the undefined symbol error like previous. The only
>  difference is "_Z9binary_opiiPFiiiE" changed to "binary_op". Could you
>  help me more on this. It seems to have a mixed problems here and I
>  guess what you've pointed out is one of them. But really, what I do
>  now is just try to reproduce the example, how can this fails? What my
>  ultimate need is wrapping up a template function taking template
>  function pointer as argument. Did you ever try that? Many thanks
>  already anyway.
> 
>  FILE and ERROR details:
> 
>  %module test
>  %{
>  #include "test.h"
>  %}
>  %include "test.h"
> 
>  %callback("%s_cb");
>  int myadd( int, int ); //myadd_cb
>  int mysub( int, int ); //mysub_cb
>  int mymul( int, int ); //mymul_cb
>  %nocallback;
> 
>  extern "C"{
>    int binary_op(int a, int b, int (*op)(int,int) );
>    int myadd( int a, int b ) { return a+b; };
>    int mysub( int a, int b ) { return a-b; };
>    int mymul( int a, int b ) { return a*b; };
>  }
> 
>  Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
>    File "test.py", line 7, in <module>
>      import _test
>  ImportError: ./_test.so: undefined symbol: binary_op

Nowhere in your code is the definition of binary_op - that is why you
get a linker error.

Is it defined in another C file?  If so you need to link it with the
swig wrapper before you make the .so

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list