On Thu, Oct 16, 2008 at 9:12 PM, Robert Bradshaw <[EMAIL PROTECTED]> wrote: > 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.
Yes, that's the problem, that I get "f" at compile time as a C function pointer. This arises when I have a C++ program that needs to call some scipy functions for integration. So I just want to create my C function and pass it to Cython->scipy->Cython->C. > If I understand right, you want an automatic python wrapper of a C > function. Perhaps it could be done, as long as the arguments and > return type could all be converted, but it's certainly not > implemented currently and easily enough done by the code you have above. Yes, but I want it to be explicit, no magic. Maybe there is some nice way to do that, if not, then we can at least add my way into the documentation as Gabriel has suggested. Ondrej _______________________________________________ Cython-dev mailing list [email protected] http://codespeak.net/mailman/listinfo/cython-dev
