On Oct 16, 2008, at 12:09 PM, Gabriel Gellner wrote:

> On Thu, Oct 16, 2008 at 07:12:11PM +0200, Ondrej Certik wrote:
>> Hi,
>>
>> I want to use scipy's quadrature like this:
>>
>> val, err = quadrature(func2, a, b, args=(f,))
>>
>> where func2 is my Cython function and "f" is a C function pointer,
>> that will get executed from func2. The problem is, that "f" is passed
>> to the Python quadrature function, so it needs to be wrapped.
>> Currently what I do is:
>>
>>
>> cdef class MyFunc:
>>     cdef f2 thisptr
>>
>>     cdef set_f(MyFunc self, f2 f):
>>         self.thisptr = f
>>
>>     cdef f2 get_f(MyFunc self):
>>         return self.thisptr
>>
>>
>> cdef MyFunc mf = MyFunc()
>> mf.set_f(f)
>> val, err = quadrature(func2, a, b, args=(mf,))
>>
>> Where func2 is:
>>
>> def func2(a, MyFunc mf):
>>     cdef f2 f = mf.get_f()
>>     return array([f(x) for x in a])
>>
>> This works nice. Is this the way to do it? Or is there some
>> better/simpler way. I don't know if it's a good idea to make Cython
>> clever enough to wrap things like this automatically?
>>
> I often just use a closure (I assume your are doing this all in  
> cython), so
> you can just have:
>
>     cdef double f(double x):
>         return x*x
>
>     def func2(a):
>         return array([f(x) for x in a])
>
>     val, err = quadrature(func2, a, b)
>
> Though I am not sure if this works in your case. When we come to a  
> consensus on
> the idiomatic way of doing this we should write up some documentation!

I believe the issue is that f needs to be received as a function  
pointer at compile time, but if I'm mistaken then this is certainly  
cleaner.

- Robert


_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to