exposing C array to python namespace: NumPy and array module.

Raymond L. Buvel levub137 at wi.rr.com
Sat Jan 1 13:18:08 EST 2005

Bo Peng wrote:
> Dear list,
> I am writing a Python extension module that needs a way to expose pieces 
> of a big C array to python. Currently, I am using NumPy like the following:
>  PyObject* res = PyArray_FromDimsAndData(1, int*dim, PyArray_DOUBLE, 
> char*buf);
> Users will get a Numeric Array object and can change its values (and 
> actually change the underlying C array).
> This works fine. However, when I deliver my module, I find NumPy is 
> unnecessarily large for this simple task. As a matter of fact, I had to 
>  build from source NumPy, ATLAS etc on Solaris, Linux, Mac.... and if a 
> user would like to use my module, he has to do the same thing!
> Python's array module is built-in, easy to use, but *without* a 
> FromLenAndData function! Even the buffer interface provides only 'get 
> buffer' but no 'set buffer' functions. Could anyone tell me how I can 
> create an array object from existing data? Some vague ideas might be 
> used: 1. PyCObject (I do not really understand the manual), 2. copy and 
> modify arraymodule.c to my project (doable at all? License issue?) 3. 
> Create an array object and hack it. (no api to do this.)
> I would strongly suggest an arraymodule.h with Array_FromLenAndData.
> Many thanks in advance.
> Bo
I don't know how much this will help but when I am faced with a problem 
like this, I use Pyrex and look at the generated code.  All you need to 
do in Pyrex is import the array module and create your array like you 
would in Python.  To get the data into the array you will need to use 
the buffer interface and fill it in from your C code.

More information about the Python-list mailing list