[PYTHON MATRIX-SIG] C API questions

Jim Hugunin hugunin@mit.edu
Tue, 5 Nov 1996 14:01:22 -0500


> But what other choice do I have? I want to define a general C-level
> interface to some of my code, which might actually be Python code.
> So I must construct a C wrapper around the Python functions. But a
> C function can't make any assumptions about the existence of its
> actual parameters after it returns. It might look like:
> 
>    double *x = malloc(n*sizeof(double));
>    do_some_calculation(x, n);
>    free(x);
> 
> with
> 
>    void do_some_calculation(double *x, int n)
>    {
>       PyArrayObject *a = PyArray_FromDimsAndData(.., x, n, ..);
>       /* call Python function working on a */
>    }
> 
> In that case I must make sure that no access to the memory pointed
> to by x can occur after my C wrapper exits.

My usual solution in this case is to copy data frequently.  I assume that
you want to modify the array x in-place here?  My own approach in these
situation has been to change my C API to something like:

do_some_calculation(x_in, x_out, n)

where x_out is allocated memory to hold the result.

then in my python code I do:

a = PyArray_FromDims
memcpy x_in into a

do calculation

get back PyArrayObject b
memcpy from b's data area into x_out

For all of the functions I've used, the impact of these memcpy's on my
performance has been too small to measure.

I actually have come to like this approach even for straight C code as it
makes many memory management issues a little bit more straightforward.

-Jim


=================
MATRIX-SIG  - SIG on Matrix Math for Python

send messages to: matrix-sig@python.org
administrivia to: matrix-sig-request@python.org
=================