cxx to NumPy Return Q

yelled at yahoo.com yelled at yahoo.com
Mon Oct 30 11:21:49 EST 2000


Hi,

I am trying to send array and get it back from CXX. I am trying to use
both PyArray_FromDimsAndData and loops and both fails. Can someone
help?

TIA,

Hoon,

My Cxx code-----------

Object ex_tNumPy(const Tuple &args) {
if(!PyArray_API) import_array() // NumPy dll is made available
float **inP; // float C++ holder for PyArray
int numGates, numRays; // # rows, cols

// cout << for input array
PyObject *theInput = args[0].ptr(); // extract PyArray
if(PyArray_As2D(&theInput, (char ***)&inP,
&numRays, &numGates, PyArray_FLOAT) != 0) {
throw RuntimeError("conversion to 2D Array of FLOAT");
}
for( int r=0; r< numRays; r++ ) {
for( int c=0; c< numGates; c++ ) {
float orig = inP[r][c];
std::cout << orig << ", ";
}
std::cout << std::endl;
}

// cout << for input array
Object tmp; // tmp goes back w/ Dict d to Python
Object tmp1; // tmp goes back w/ Dict d to Python
PyArrayObject *arry = NULL;
PyArrayObject *arry1 = NULL;
int dims[2] = {numRays, numGates};

arry = (PyArrayObject *)PyArray_FromDimsAndData(2, dims, PyArray_FLOAT,
(char *)inP); //********************HERE***************************

arry1 = (PyArrayObject *)PyArray_FromDims(2, dims, PyArray_FLOAT);
for( r=0; r< numRays; r++ ) {
for( int c=0; c< numGates; c++ ) {
int ix = r*2+c; // addr[r,c] of PyArrayObj
float orig = inP[r][c] + 1.5;
((float *)arry1->data)[ix] = Float(orig);
//float *fPtr = &((float *)pa->data)[swpbeams*numGates];
std::cout << r << ","<< c <<" | "<< ix << " " << orig << std::endl;
}
}


Dict d;
tmp = Object((PyObject *)arry);
tmp1 = Object((PyObject *)arry1);
d["RetData"] = tmp;
d["RetData1"] = tmp1;
d["numRays"] = Int(numRays);
d["numGates"] = Int(numGates);
free(inP);
Py_DECREF(theInput); // PyArray_As2D increments
Py_DECREF(arry);
Py_DECREF(arry1);
return d;
}

----tst.py-------
import PCACxx as E
import Numeric as N

ary = N.arange(9).astype('f')
ary = N.reshape(ary,(3,3))
rst = E.tNumPy(ary)
print rst

0, 1, 2,
3, 4, 5,
6, 7, 8,
0,0 | 0 1.5
0,1 | 1 2.5
0,2 | 2 3.5
1,0 | 2 4.5
1,1 | 3 5.5
1,2 | 4 6.5
2,0 | 4 7.5
2,1 | 5 8.5
2,2 | 6 9.5
{'RetData1': array([[ 1.5, 2.5, 4.5],
[ 5.5, 7.5, 8.5],
[ 9.5, 0. , 0. ]],'f'), 'numGates': 3, 'RetData': array([[ 1.19980071e-
038, 1.19980240e-038, 1.19980408e-038],
[ 3.30046146e-038, 2.10194770e-044, 0.00000000e+000],
[ 4.62428493e-044, 6.86636248e-044, 1.20041953e-038]],'f'), 'numRays':
3}


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list