[Numpy-discussion] passing a C array to embedded Python from C code

Christopher Barker Chris.Barker@noaa....
Thu Oct 30 13:00:31 CDT 2008


A few comments:

Chris LeBlanc wrote:
>  I'm thinking I could create a
> NumPy array that uses the same C array (1d, 2d, or 3d) that our
> program is using instead of copying the memory.

yes, you can do that.

> At this point, I'm thinking the python code wouldn't need to return
> any objects because it would be modifying the seismic data (and trace
> headers) in memory.

There are a number of operations in Python that would require copies of 
the data, and you may want to be able to create data in python, and 
process it with your C code, so you probably do want to support passing 
data arrays from Python to the C code as well.


> Maybe calling a custom module from the Python code that does the C
> array to NumPy translation using Cython/pyrex/swig/etc.  Would it be
> possible to use the same C arrays from here without copying them?

yes, and you probably do want to use one of Cython, SWIG, or Ctypes -- 
it's really easier not to have to handle the reference counting, etc, 
yourself.

There are a set of SWIG typemaps and docs in the numpy distribution (in 
the docs dir, I believe), and there are various Wiki pages describing 
how  to do it with Cython and ctypes as well.

How to choose?

My thoughts on SWIG: SWIG is a pretty complex system, so you need to 
learn what is essentially yet another language. However, the numpy.i 
typemaps work well for the simple cases, so it may be easy to get 
started. The big advantage of SWIG is that it auto-generates the 
wrapper, once you have defined the typemaps you need. This gives a real 
advantage if you need to :

- provide wrappers for more than one language (PERL, Java, etc..)

- are wrapping a substantial library, particularly one that is under 
active development.

-Chris



-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker@noaa.gov


More information about the Numpy-discussion mailing list