passing callback function to c-extension

D

Diez B. Roggisch

Hi,

I'm currently writing my first c-extension module. First of all: distutils
and the tutorial for embedding/extending rock! Great work, guys.

However, I didn't find a hint how to pass a python callback function.
Googling didn't turn out much useful stuff, so I'd be glad if someone could
post a hint on how to do this.

Regards,

Diez
 
E

Eric Brunel

Diez said:
Hi,

I'm currently writing my first c-extension module. First of all: distutils
and the tutorial for embedding/extending rock! Great work, guys.

However, I didn't find a hint how to pass a python callback function.
Googling didn't turn out much useful stuff, so I'd be glad if someone could
post a hint on how to do this.

A Python function is just a regular Python object, so it is represented at C
level by a PyObject*. To call it from C, just use one of the PyObject_Call
functions - see http://www.python.org/doc/current/api/object.html#l2h-189

HTH
 
D

Diez B. Roggisch

Hi,
A Python function is just a regular Python object, so it is represented at
C level by a PyObject*. To call it from C, just use one of the
PyObject_Call functions - see
http://www.python.org/doc/current/api/object.html#l2h-189

Thanks - works like a charm. I'm now looking for a way to ensure that the
passed object is actually a callable one - and how to throw exceptions. But
I just started looking for that, so I'll be back if I really need help.

Diez
 
S

Skip Montanaro

Diez> I'm now looking for a way to ensure that the passed object is
Diez> actually a callable one

Try it and see. If an exception is raised, just return NULL. The
appropriate exception stuff will have been set.

Alternatively, you can test the value of

PyCallable_Check(obj)

to see if obj is really callable and do your own error recovery.

- and how to throw exceptions.

The C API manual is your friend here:

http://www.python.org/doc/api/api.html

Search for "exception".

Skip
 
D

Diez B. Roggisch

Diez> I'm now looking for a way to ensure that the passed object is
Diez> actually a callable one

Try it and see. If an exception is raised, just return NULL. The
appropriate exception stuff will have been set.

Thanks - I already found out about that. Its incredible - a few hours of
work (mostly because I've actually have to _learn_ something new, not
because of the api makes things complicated) and I've got my wrapper. If I
can keep up that pace, I'll release my wrapper this night, or tomorrow :)

Regards,

Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,765
Messages
2,569,568
Members
45,042
Latest member
icassiem

Latest Threads

Top