Mailing List Archive

callbacks/functions pt 2?
Yesterday, I got part of my answer about passing a python function to a
C/c++ class. But, what was left out was passing the Python function to the
c/c++ program, the docs did the same thing unless I skipped it.
Ex. This is taken from a modified beer.py

import testmeth
n = 20
#if sys.argv[1:]: n = int(sys.argv[1])

def setN(x): #this is the function I want to send to C/C++
x = n

def bottle(n):
if n == 0: return "no more bottles of beer"
if n == 1: return "one bottle of beer"
return str(n) + " bottles of beer"

testmeth.testmeth(13,9)
testmeth.test(setN) #Here I am trying to make the call to my C/C++
function, but I get an error
for i in range(n):
print bottle(n-i), "on the wall,"
print bottle(n-i) + "."
print "Take one down, pass it around,"
print bottle(n-i-1), "on the wall."

print n
callbacks/functions pt 2? [ In reply to ]
Jr King <n@n.com> writes:

> Yesterday, I got part of my answer about passing a python function to a
> C/c++ class. But, what was left out was passing the Python function to the
> c/c++ program, the docs did the same thing unless I skipped it.

This is covered in the 'Extended and Embedding' document, including a
code sample, in the section 'Calling Python Objects from C.'

What is mentioned in that section, but not directly shown, is that you
also need to add my_set_callback() to the method table you use with
Py_InitModule(), something like:

static PyMethodDef MyMethods[] = {
{"set_callback", my_set_callback, METH_VARARGS},
{"some_other_function", useful_function, METH_VARARGS},
{NULL, NULL}
};

To set the pointer so that C can use it, your Python script first
imports the C module, then passes the object to my_set_callback, like
so:

def thingy(aNumber):
return aNumber + 1

import my_c_module
my_c_module.set_callback(thingy)


This relationship borders on kinky, but hey, it works.