Calling Python functions from inline C with scipy.weave
Question: Can I call a python function from inline C code (using weave)?

Motivation: I have a bit of code that I'd like to optimize, and I've
identified the bottleneck in one function. After my usual tricks, I usually
turn to
[scipy.weave.inline](http://docs.scipy.org/doc/scipy/reference/generated/scipy.weave.inline.html)
for optimization. Unfortunately, in this case, my function is calling another
python function in an inner loop. I've made sure that the inner function isn't
causing the speed issue, and I really don't want to have to write it in C as
well.

Minimal Example:

    
    
    from weave import inline
    
    def foo(x):
        return x*2
    
    def bar():
        a = 0
        for i in xrange(10):
            a += foo(i)
        return a
    
    def bar_weave():
        code = """
        int a = 0;
        for (int i=0;i<10;++i){
            a += foo(i);  //<<-- what I'd like to do, but doesn't work
        }
        return_val = a;"""
        return inline(code,['foo'])
    
    print bar()
    print bar_weave()
    


Answer: It's a little involved, as Weave doesn't have a way to automatically marshall
the arguments and return value. You need to do a little more work:

    
    
    def bar_weave():
        code = """
        int a = 0;
        for (int i=0;i<10;++i){
            py::tuple arg(1);
            arg[0] = i;
            a += (int) foo.call(arg);
        }
        return_val = a;
        """
        return inline(code,['foo'])
    

Output:

    
    
    90
    

