Interfacing python and C

Nick Craig-Wood nick at craig-wood.com
Sat Mar 28 13:30:03 CET 2009


MRAB <google at mrabarnett.plus.com> wrote:
>  steve William wrote:
> > Hi All,
> > 
> > I'm using SWIG for the first time and I am facing some problems with 
> > user defined header files. I'm trying to use my own header file in a C 
> > program which would be interfaced with python.
> > 
> > The header file is test.h:
> > /#include <stdio.h>
> > 
> > int fact(int n) {
> >      if (n <= 1) return 1;
> >      else return n*fact(n-1);
> > }/
> >    
> > The C program is test1.c:
> > /#include <stdio.h>
> > #include "test.h"
> > 
> > int calc_fact(int a)
> > {
> >     return (fact(a));
> > }/
> > 
> > The interface file is test1.i:
> > /%module test1
> > 
> > %{
> > #include "stdio.h"
> > #include "test.h"
> >  %}
> > 
> > int calc_fact(int a);/
> > 
> > The commands that I used to generate the wrappers are:
> > /swig -python test1.i
> > gcc -c test1.c test1_wrap.c -I/usr/include/python2.5 
> > -I/usr/lib/python2.5/config
> > g++ -shared test1_wrap.o -o _test1.so/

gcc not g++ here

link test1.o also

gcc -shared test1.o test1_wrap.o -o test1.so

> > When I try to import test1, I get an error saying:
> > />>> import test1
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in <module>
> >   File "test1.py", line 22, in <module>
> >     import _test1
> > ImportError: ./_test1.so: undefined symbol: calc_fact/

Try nm or objdump on the .so to see what symbols are in it.

> > I'm not sure why this is happening because when I try without user 
> > defined header file, it works. Also the error says that it does not 
> > recognize /calc_fact/ which is a function that I want to access from 
> > python and is declared in the interface file.
> > 
> > Is there any specific way in which user defined headers need to be 
> > declared in the interface file? Should the user defined header be placed 
> > in the /usr/include  directory?
> > 
> > Any help on this is highly appreciated.

My advice to you is to compile the C stuff into a .so and use ctypes
instead of swig.  You then write the interface code in python not C
and you'll have a lot more fun!

cython is very useful in this area too provided you don't mind an
extra dependency.  If you are developing C code from scratch to
use with python, then write it in cython instead!

>  Should you be putting a function body in a header file?

No

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



More information about the Python-list mailing list