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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With