Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.