From: James B. <bi...@cs...> - 2006-04-24 19:59:01
|
James Bigler wrote: > I'm trying to make some python callbacks from C. So far I wrote a > simple interface by hand (not using swig) that allows me to pass a > function and its arguments from python to C. I create an class object > (called MyPyCallback) with PyObject pointers to the function and args > and pass that back in a PyCObject. This can then be stored in python or > in C and used to call the function later. > > Now I have an interface generated by swig that provides all sorts of > access to callback mechanisms. I need a way to pass this PyCObject > through the interface to make it into something I can pass around. > > My question is how I can pass the PyObejct*'s directly through the > interface. If need be I can make a wrapper for MyPyCallback, in which > case all I need is a way to get the void* in the PyCObject into a > Swigged MyPyCallback*. > > Any pointers to where I should look in the documentation or other help > would be appreciated. After reading pages and pages of the documentation, I discovered I could do this through %typemap. Here is some simple code that counts the number of items in a tuple passed in: %typemap(in) PyObject* { $1 = $input; } // This is for other functions that want to return a PyObject. %typemap(out) PyObject* { $result = $1; } int countTuple(PyObject* args); %{ int countTuple(PyObject* args) { if (!PyTuple_Check(args)) { fprintf(stderr, "Not a Tuple\n"); return 0; } int num_args = PyTuple_Size(args); return num_args; } %} ====================================================== I don't care that this isn't language portable, since I just want to use python. I now have a class that stores pointers to python functions and their arguments, that I can call later from C. Thanks, James |