Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Python functions from inline C with scipy.weave

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 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()
like image 431
perimosocordiae Avatar asked May 08 '11 19:05

perimosocordiae


1 Answers

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
like image 158
samplebias Avatar answered Nov 18 '22 23:11

samplebias