Numeric Python and C

O

Ognen Duzlevski

Hi,
can someone explain how to change a value within an array from a C function?

For example, I have the following array:

scoremat = zeros((10,10))

and the following C function:

PyObject *DynAlign(PyObject *self, PyObject *args)
{
PyArrayObject *p;
int ok;

/* get the array */
ok = PyArg_ParseTuple(args,"O!", &PyArray_Type, &p);
/* this gets a value p[5][5] */
v55 = *(double *)p->data + 5*p->strides[0] + 5*p->strides[1]);
}

How to I change the value at p[5][5] and retain it in the same array after function exit?

So, from Python I might have:

from Numeric import *

scoremat = zeros((10,10))
DynAlign(scoremat)
print scoremat[5][5]

Thank you,
Ognen
 
S

Simon Burton

Hi,
can someone explain how to change a value within an array from a C
function?

What about using PyObject_GetItem (is that what it's called?)

I know numarray uses functions for this:

PyArrayObject* NA_InputArray( PyObject *numarray, NumarrayType t, int requires)
The purpose of NA_InputArray is to transfer array data from Pythonto C.

PyArrayObject* NA_OutputArray( PyObject *numarray, NumarrayType t, int requires)
The purpose of NA_OutputArray is to transfer data from C to Python. Practically speaking, the output numarray must be a PyArrayObject, and cannot be an arbitrary Python sequence.

PyArrayObject* NA_IoArray( PyObject *numarray, NumarrayType t, int requires)
NA_IoArray has fully bidirectional data transfer, creating the illusion of call-by-reference.


Simon.
 
J

John Hunter

Ognen> Hi, can someone explain how to change a value within an
Ognen> array from a C function?

Warning: I am not a Numeric C API guru.

For 1D arrays I use the following macro

// get x from a 1d array of type xtype
#define get1d(x,i,xtype) \
*(xtype *)(x->data+i*x->strides[0])


You can assign to the return value of this, as in

count = 0;
while ((row = mysql_fetch_row(res)) != NULL) {
get1d(p,count,float) = atof(row[0]);
get1d(v,count,int) = atoi(row[1]);
++count;
}

where p and v are 1D numeric arrays.

You'll have to do a bit more work for 2D arrays, but this may speed
you on your way....

JDH
 
O

Ognen Duzlevski

Ognen> Hi, can someone explain how to change a value within an
Ognen> array from a C function?
Warning: I am not a Numeric C API guru.
For 1D arrays I use the following macro [snipped]
You'll have to do a bit more work for 2D arrays, but this may speed
you on your way....

Hi, for 2D arrays it is much similar:

get(ndx1,ndx2): array->data + ndx1*array->strides[0] + ndx2*array->strides[1]
set(ndx1,ndx2): I use memcpy(same as get, &val, sizeof(val);

Thanks,
Ognen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top