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

Chris LeBlanc crleblanc@gmail....
Wed Oct 29 23:55:29 CDT 2008


Hello,

I'm working on seismic processing software called Globe Claritas.  The
core is written in C and a bit of Fortran.  I would like to embed
Python in this software, so a user can use Python code to manipulate
the seismic data.  This would give our users all the power of Python
and NumPy and any external modules they may want to use.

I was thinking I could use the Python C API to initialize Python and
run the code supplied by the user.  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.  Perhaps using the
NumPy API function PyArray_SimpleNewFromData() or something similar
(similar to this posting: http://blog.enthought.com/?p=62).  I would
then pass this NumPy array as an object to the Python code, which it
could manipulate.  The C array is an array of floating point data
samples for each seismic trace, so hopefully well suited to this.

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.

Does this approach make sense?  Is there a better way to go about it?
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?

Is there a more obvious way to do it that I might be missing?  Does
anyone have examples of creating a NumPy array in C, and passing it to
a Python instance?  That would be a huge help, I have no experience
with the C or NumPy APIs.

Thanks,
Chris LeBlanc


More information about the Numpy-discussion mailing list