Pass numeric arrays from C extensions to Python

Oscar Benjamin oscar.j.benjamin at gmail.com
Sun Sep 23 22:11:08 EDT 2012


On 24 September 2012 02:39, JBT <jianbao.tao at gmail.com> wrote:

> Hi,
>
> I am looking for a way to pass numeric arrays, such as *float a[100];
> double b[200];*, from C extension codes to python. The use case of this
> problem is that you have data stored in a particular format, NASA common
> data format (CDF) in my case, and there exists an official C library to
> read/create/edit such data, and you want to do data analysis in python. The
> problem comes down to how to feed the data into python.
>

You probably want to wrap the c arrays in numpy.ndarray objects that can
then be accessed manipulated from Python. Numpy has a function that (I
think) does what you want called PyArray_SimpleNewFromData:
http://docs.scipy.org/doc/numpy/reference/c-api.array.html#PyArray_SimpleNewFromData

I recommend using Cython to create any extension modules that interact with
C libraries. In Cython you can:
1) Use the above function to create a numpy array.
2) Manipulate c-pointers directly to extract their data and insert it into
a standard Python container.
3) Write a simple extension type to wrap the pointer into an array type
that is accessible from Python.

In any case it seems that someone has already made a Python library for
accessing CDF data, called pycdf (I have no experience of using this
library):
http://spacepy.lanl.gov/doc/pycdf.html

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120924/62c97b34/attachment.html>


More information about the Python-list mailing list