This should be a trivial question, but didn't figure out as a beginner.
I have the following Python C-extenstion using numpy arrays:
#include <cmath>
#include <Python.h>
#include <iostream>
#include "numpy/arrayobject.h"
using namespace std;
PyObject *func_calc(PyObject *self, PyObject *args)
{
PyObject * PO_clmn;
PyArrayObject * py_clmn;
if (!PyArg_ParseTuple(args, "O", &PO_clmn))
return NULL;
py_clmn = (PyArrayObject*)PyArray_ContiguousFromObject(PO_clmn,PyArray_DOUBLE,1,1);
double *clmn = (double*)(py_clmn->data);
int i;
int N = py_clmn->dimensions[0];
int flag_threadholds[N_threadholds];
for (i=0; i<N; i++)
{
clmn[i]=1;
}
return Py_None;
}
static PyMethodDef exampleMethods[] =
{
{ "calc", func_calc, METH_VARARGS },
{ NULL, NULL }
} ;
PyMODINIT_FUNC initcalc()
{
import_array();
Py_InitModule("calc", exampleMethods);
}
After compiling it as a shared library, I found the following call failed to modify the element clmn array to "1":
import numpy
from calc import calc
clmn=numpy.zeros(10)
calc(clmn)
print clmn #[0,0...
Thanks in advance!
Depending on the data you pass in, the call to PyArray_ContiguousFromObject
may return the original object, or it may return a copy of the object. If it returns a copy, then your code is modifying that copy, not the original object.