Python Function pointer in C

David Gilbert dgilbert at dclg.ca
Tue Nov 23 17:10:07 EST 2004


I'm trying to maintain the interface to KQueue for FreeBSD.  At one
point, the C module stores an opaque object in a C structure such that
the opaque pointer can be used later by the application.

In Python, I want to say something like:

        kev = [KEvent(1000, filter=EVFILT_TIMER, flags=EV_ADD|EV_ONESHOT,
                     udata=lambda x: getJob(x, con))]
        kq.event(kev, 0, 0)

and later, this is used by 

    kev = kq.event(None, 1, 0)
    print "Kevent Triggered! %s" % str(kev)

    # Call event's udata
    kev.udata(kev)

... so this doesn't work.  Specifically:

[3:4:304]dgilbert at canoe:~/devel/SoftGrabber> python
Python 2.3.4 (#2, Nov  2 2004, 16:03:35) 
[GCC 3.4.2 [FreeBSD] 20040728] on freebsd5
Type "help", "copyright", "credits" or "license" for more information.
>>> import kqsyscall 
>>> from kqsyscall import *
>>> kq = kqueue()
>>> kev = kevent(1000, EVFILT_TIMER, EV_ADD+EV_ONESHOT, 0, 0, lambda x: x+1)
>>> kev
<KQEvent ident=1000 filter=-7 flags=11 fflags=0 data=0 udata=0x81b4fb4>
>>> kev.udata
<function <lambda> at 0x81b4fb4>
>>> kev.udata(1)
Segmentation fault (core dumped)

Now the code in the C module (kqsyscall above) defines the kevent()
return as the following object:

static struct memberlist KQEvent_memberlist[] = {
  {"ident",     T_UINT,         OFF(e.ident)},
  {"filter",    T_SHORT,        OFF(e.filter)},
  {"flags",     T_USHORT,       OFF(e.flags)},
  {"fflags",    T_UINT,         OFF(e.fflags)},
  {"data",      T_INT,          OFF(e.data)},
  {"udata",     T_OBJECT,       OFF(e.udata)},
  {NULL}        /* Sentinel */
};

And it also defines various support functions.

How do I define "udata" such that I can stuff the lambda reference in
there?

Now... I've wondered if this is a reference counting issue --- but
this still happens when I use the name of a module global function as
udata.

Dave.

-- 
============================================================================
|David Gilbert, Independent Contractor.       | Two things can only be     |
|Mail:       dave at daveg.ca                    |  equal if and only if they |
|http://daveg.ca                              |   are precisely opposite.  |
=========================================================GLO================



More information about the Python-list mailing list