On Mon, Oct 13, 2008 at 6:33 PM, Dag Sverre Seljebotn
<[EMAIL PROTECTED]> wrote:
> Dag Sverre Seljebotn wrote:
>> Ondrej Certik wrote:
>>>
>>> cdef inline ndarray array_d(int size, double *data):
>>> #cdef ndarray ary2 = PyArray_ZEROS(1, &size, 12, 0)
>>> cdef ndarray ary = zeros(size, dtype=float64)
>>> if data != NULL: memcpy(ary.data, data, size*sizeof(double))
>>> return ary
>>>
>>> cdef inline int iarray_d(ndarray a, int *size, double **data) except -1:
>>> if a.dtype != float64:
>>> raise TypeError("The array must have the dtype=float64.")
>>> if size!=NULL: size[0] = a.dimensions[0]
>>> if data!=NULL: data[0] = <double *> (a.data)
>>>
>
>> HOWEVER, note that your iarray_d will only work if the array that is
>> passed in is contiguous. So you should either a) insert an assertion of
>> a.flags['C_CONTIGUOUS'] at the beginning, or b) fix it so that it works
>> with all arrays (as by my example).
>>
>> Any non-trivial NumPy usage is likely to end up with non-contiguous
>> arrays, so if the "a" argument could come from the end-user somehow then
>> choking on non-contiguous arrays is not going to work well.
>>
>>
>
> Note that this is non-trivial since any copy made must also not be
> deallocated, so that iarray_d would have to return a reference which
> must be held on to for the duration of using the buffer data.
>
> If you need to accept ndarrays coming from the user, a better idiom is
> likely to take a callback function which will be called with the buffer
> as an argument, or similar -- returning the buffer through a double**
> (or np.float64_t**) is rather error-prone when it comes to reference
> counting.
Yeah, I thought pretty much along the same lines.
Basically, I am fine if the function raises an exception on
noncontiguous arrays and/or copy the array automatically, so that's
not an issue.
The big problem is with the reference counting, i.e. who is
reposnsible for freeing the double** memory. Basically, the memory is
automatically freeed when the numpy array goes out of scope, right? So
basically, the rule is: either do something with the double** array
immediatelly (in C/C++) on the fly, or make a copy of it if you need
it longer. Another option would be to Py_IncRef/DecRef the numpy array
to make sure the C array is not recycled.
Ondrej
_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev