multidimensional arrays from python to C
Fernando PĂ©rez
fperez528 at yahoo.com
Wed May 29 13:22:40 EDT 2002
Chris Fonnesbeck wrote:
> I am embedding some python code in C, and need to be able to take a
> multidim. array from python and assign its values to a global double
> array in C. Can this python array simply be cast into a C double
> type, and assigned to the array in question, or do I have to do a
> multiple-nested loop to assign each element individually. Hope this
> makes sense!
You should take a look at weave (scipy.org). It allows you to write things
like:
#-----------------------------------------------------------------------------
# Returning a scalar quantity computed from a Numeric array.
def trace(mat):
"""Return the trace of a matrix.
"""
nrow,ncol = mat.shape
# The following is embedded C code:
code = \
"""
double tr=0.0;
for(int i=0;i<nrow;++i)
tr += mat(i,i);
return_val = Py::new_reference_to(Py::Float(tr));
"""
return weave.inline(code,['mat','nrow','ncol'],
type_converters = converters.blitz)
If you look at http://www-hep.colorado.edu/~fperez/python/python-c/ you'll
find some examples of basic weave usage which should get you started in 10
minutes.
Cheers,
f.
More information about the Python-list
mailing list