[Numpy-discussion] numpy.ctypeslib.ndpointer and the restype attribute [patch]
Thu Mar 26 06:41:28 CDT 2009
On Mon, 2009-03-23 at 14:36 +0100, Jens Rantil wrote:
> So I have a C-function in a DLL loaded through ctypes. This particular
> function returns a pointer to a double. In fact I know that this
> pointer points to the first element in an array of, say for
> simplicity, 200 elements.
> How do I convert this pointer to a NumPy array that uses this data
> (ie. no copy of data in memory)? I am able to create a numpy array
> using a copy of the data.
Just a follow up on this topic:
While constructing a home made __array_interface__ attribute does the
job of converting from a ctypes pointer to a NumPy array, it seems both
like an undocumented and magic solution to a common problem.
Therefor, I used the code that Sturla Molden posted and wrote a highly
useful piece of code that enables ctypes DLL functions to return NumPy
arrays on the fly. See it as a replacement for the incorrectly
documented ndpointer/restype functionality if you want. The code is
attached with the mail, including Nose tests.
An example workflow to have a ctypes DLL function return a 4 element
double array would be:
>>> returns_ndarray(dll.my_func, ctypes.c_double, 4)
>>> my_array = dll.my_func()
array([ 2.1, 4. , 97. , 6. ])
Notice that 'my_array' will be sharing the memory that the DLL function
returned. Also, I have not done extensive testing of ndim and shape
Wouldn't my code, or a tweak of it, be a nice feature in
numpy.ctypeslib? Is this the wrong channel for proposing things like
Lund University & Modelon AB, Sweden
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 5148 bytes
Desc: not available
Url : http://mail.scipy.org/pipermail/numpy-discussion/attachments/20090326/566fefc5/attachment-0001.py
More information about the Numpy-discussion