[Numpy-discussion] How to call methods from a class with custom matrices parameters with numpy arrays ?

David Cournapeau david@ar.media.kyoto-u.ac...
Thu Apr 19 06:15:04 CDT 2007


Matthieu Brucher wrote:
>
>         You should give ctypes a try, I find it much better than swig most
>     of the time for wrapping. You can find some doc here:
>
>         http://www.scipy.org/Cookbook/Ctypes2
>
>         Basically, once you get your dll/so with a function foo(double *a,
>     int n), you can call it directly in numpy by passing directly a numpy
>     array. The catch is that the layout of the array should be exactly the
>     same than your function expects (most of the time a contiguous array),
>     but there are numpy functions which enforce that. As long as you
>     are not
>     calling thousand of function with small arrays, the wrapping is pretty
>     efficient in my experience.
>
>         cheers,
>
>         David
>
>
>
> Thanks for the fast answer ;)
> I was wondering if ctypes would fit better, but in this case, I have 
> to make the wrapper myself, I suppose ?
> Here is the basic prototype of what I have - it's a cost function I 
> want to optimize with optimizers I proposed on scipy recently - :
>
> template<class MatrixType>
> struct CostFunction
> {
>   CostFunction(const MatrixType& points, ...)
>   {
>   }
>
>   const MatrixType gradient(const Matrixtype& parameters)
>   {
>     // ...
>     return aNewGradient;
>   }
> };
>
> So I have to create a function that takes a numpy array and that 
> returns and instance of my cost function, this is pretty simple to do, 
> the matrix can be constructed from its two dimensions and a pointer, 
> but for the gradient method, I have trouble seeing how to do wrap it :(
I forgot you are using C++. Using C++ with ctypes makes the wrapping 
more difficult, I think, specially since you are using templates: you 
would have to write a C wrapper around your classes, and then using 
ctypes on the wrapper (there may be better ways, but I don't see an 
obvious one). Basically, using ctypes is like using code from a 
dynamically loaded library (ala VST :) ). But writing some C code kills 
one of the strong point of ctypes (doing all the wrapping in python).

I have attached a simplistic example which show how to wrap some functions.

David
-------------- next part --------------
A non-text attachment was scrubbed...
Name: example.tbz2
Type: application/x-bzip-compressed-tar
Size: 4581 bytes
Desc: not available
Url : http://projects.scipy.org/pipermail/numpy-discussion/attachments/20070419/90314be3/attachment-0001.bin 


More information about the Numpy-discussion mailing list