[Numpy-discussion] C++ class encapsulating ctypes-numpy array?
Thu Mar 20 08:42:18 CDT 2008
2008/3/20, Joris De Ridder <Joris.DeRidder@ster.kuleuven.be>:
> Thanks Matthieu, for the interesting pointer.
> My goal was to be able to use ctypes, though, to avoid having to do manual
> memory management. Meanwhile, I was able to code something in C++ that may
> be useful (see attachment). It (should) work as follows.
> 1) On the Python side: convert a numpy array to a ctypes-structure, and
> feed this to the C-function:
> arg = c_ndarray(array)
> 2) On the C++ side: receive the numpy array in a C-structure:
> myfunc(numpyArray<double> array)
> 3) Again on the C++ side: convert the C-structure to an Ndarray class: (
> e.g. for a 3D array)
> Ndarray<double,3> a(array)
> No data copying is involved in any conversion, of course. Step 2 is
> required to keep ctypes happy. I can now use a[i][j][k] and the conversion
> from [i][j][k] to i*strides + j * strides + k * strides is done at
> compile time using template metaprogramming. The price to pay is that the
> number of dimensions of the Ndarray has to be known at compile time (to
> instantiate the template), which is reasonable I think, for the gain in
> convenience. My first tests seem to be satisfying.
> I would really appreciate if someone could have a look at it and tell me
> if it can be done much better than what I cooked. If it turns out that it
> may interest more people, I'll put it on the scipy wiki.
You can use ctypes if and ony if the C++ object is only used in one function
call. You can't for instance create a C++ container with ctypes, then in
Python call some method and then delete the container, because ctypes will
destroy the data after the C++ container was built. This is the only
drawback of ctypes.
When it comes to strides, you have to divide them by the size of your data :
the stride is counted in bytes and not in short/float/...
French PhD student
Website : http://matthieu-brucher.developpez.com/
Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
LinkedIn : http://www.linkedin.com/in/matthieubrucher
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Numpy-discussion