wrapping C functions in python

Brian Cole coleb2 at gmail.com
Wed Apr 9 16:55:43 EDT 2008


SWIG is a program that automatically generates code to interface
Python (and many other languages)  with C/C++. If you plan to create
lasting software libraries to be accessed from Python and C it is
quite a robust way to do so. Essentially, you feed it header files,
compile your code and the code generated by swig as a shared library,
then import the functions like you would a normal python module.

If all you need is to make some numerical code run faster it may be
more of a learning curve then you bargain for. Perhaps trying NumPy is
more appropriate. http://numpy.scipy.org/

-Brian

On Wed, Apr 9, 2008 at 2:44 PM, Paul Anton Letnes
<paul.anton.letnes at gmail.com> wrote:
> Hi, and thanks.
>
>
>  However, being a newbie, I now have to ask: What is SWIG? I have heard the
> name before, but haven't understood what it is, why I need it, or similar.
> Could you please supply some hints?
>
>
>  -Paul
>
>
>  Den 9. april. 2008 kl. 22.22 skrev Brian Cole:
>
>
> >
> >
> >
> > We use the following SWIG (www.swig.org) typemap to perform such
> operations:
> >
> > %typemap(in) (int argc, char **argv) {
> > if (!PySequence_Check($input)) {
> >  PyErr_SetString(PyExc_ValueError,"Expected a sequence");
> >  return NULL;
> > }
> > $1 = PySequence_Length($input);
> > $2 = (char**)alloca($1*sizeof(char*));
> > for (Py_ssize_t i = 0; i < $1; ++i) {
> >  PyObject *o = PySequence_GetItem($input, i);
> >  $2[i] = PyString_AsString(o);
> > }
> > }
> >
> > That one works for mapping a python sequence (such as a list) into the
> > argc, argv arguments commonly passed into main.
> >
> > -Brian
> >
> > On Wed, Apr 9, 2008 at 2:13 PM, Paul Anton Letnes
> > <paul.anton.letnes at gmail.com> wrote:
> >
> > > Hello etc.
> > >
> > >
> > > I am a "scientific" user of Python, and hence have to write some
> performance
> > > critical algorithms. Right now, I am learning Python, so this is a
> "newbie"
> > > question.
> > >
> > > I would like to wrap some heavy C functions inside Python, specifically
> a
> > > wavelet transform. I am beginning to become aquainted with the functions
> > > PyArg_ParseTuple() and Py_BuildValue(). However, I am unable to figure
> out
> > > how to pass Python list -> C function or C array -> return value in
> Python.
> > > I manage to build and run the C function, print to screen, pass string
> as
> > > argument, return an int, etc. The thing which is missing is the magic
> > > array/list...
> > >
> > >
> > > Thanks in advance! I fart in your general direction.
> > > Paul.
> > > --
> > > http://mail.python.org/mailman/listinfo/python-list
> > >
> > >
> > --
> >
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
>



More information about the Python-list mailing list