[SciPy-dev] Can I call Python-functions from """code"""?

eric eric at scipy.org
Thu Jan 24 11:57:56 CST 2002


Hey Andreas,

> Is there a way to cll my self-defined Python-functions from the embeded C++ 
> code??

You can.  Since code is all C++ code, and your wanting to call a Python function, you have to do two things:

    1.  Pass the function you want to call as an argument to inline.
    2.  Call the function using the Python API.

Take note that the call back into Python exacts a large performance toll, so you probably won't see much speed up.

> 
> And if so, how???
> 

Here is an example from weave/examples/functional.py that is similar to Python's builtin map().  There is a 2nd "prettier" version in functional.py, but it is half the speed of the standard map() function.  

    def c_list_map2(func,seq):
        """ Uses Python API more than CXX to implement a simple map-like function.
            It does not provide any error checking.
        """
        code = """
               Py::Tuple args(1);    
               Py::List result(seq.length());
               PyObject* item = NULL;
               PyObject* this_result = NULL;
               for(int i = 0; i < seq.length();i++)
               {
                  item = PyList_GET_ITEM(seq.ptr(),i);
                  PyTuple_SetItem(args.ptr(),0,item);
                  this_result = PyEval_CallObject(func,args.ptr());
                  PyList_SetItem(result.ptr(),i,this_result);              
               }           
               return_val = Py::new_reference_to(result);
               """   
        return inline_tools.inline(code,['func','seq'])
    
    seq = ['aadasdf'] * 5
    result = c_list_map2(len,seq)

If you can re-write the function you need to call as a C function, then you can call it directly in C to get the speed back.  There are many cases where this isn't feasible, but some where it is.  Use the support_code key variable for this.  I think there are some examples of this in weave/examples/fibonacci.py

Hope that helps,

eric

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/scipy-dev/attachments/20020124/e1669c59/attachment.html 


More information about the Scipy-dev mailing list