2

I wrote an extension for Python 3 in C++

My module is capable of handling arrays like [1.0, 0.0, 0.0]. I want to add support for numpy arrays as well.

I process arrays with the following code:

PyObject * MyFunction(PyObject * self, PyObject * args) {
    PyObject * list;

    if (!PyArg_ParseTuple(args, "O!:MyFunction", PyList_Type, &list)) {
        return 0;
    }

    int count = (int)PyList_Size(list);
    for (int i = 0; i < count; ++i) {
        double value = PyFloat_AsDouble(PyList_GET_ITEM(list, i));

        // ...
    }
}

I want a function that can iterate through this: np.array([2,3,1,0])

TL;DR:

Numpy equivalent for:

  • PyList_Type
  • PyList_Size
  • PyList_GET_ITEM or PyList_GetItem
9
  • 1
    No real answer and maybe you got good reasons to use this native way of interfacing c++, but did you consider cython. This makes all that stuff much easier/nicer and is used by some very cool projects (e.g. scikit-learn). Commented Jul 31, 2016 at 18:03
  • normally, it's the other way round: you write a numpy-function, which also can handle lists. Commented Jul 31, 2016 at 18:04
  • I just wan't to be able to iterate through a numpy array in C++ Commented Jul 31, 2016 at 18:11
  • Now I will check cython @sascha Commented Jul 31, 2016 at 18:12
  • 1
    I'm not an expert, but what's the problem there? Cython surely needs a C++ compiler (which could be awkward for windows-users) if you are interfacing C++ code, but the same should apply to the native-bindings. A lot of projects use cython and are available on PyPI. Commented Jul 31, 2016 at 18:18

1 Answer 1

1

First of all there is no numpy equivalent for:

  • PyList_Type
  • PyList_Size
  • PyList_GET_ITEM or PyList_GetItem

The numpy.array implements the buffer interface, so one can write:

const char * data;
int size;

PyArg_ParseTuple(args, "y#:MyFunction", &data, &size);

The numpy.array([1.0, 0.0, 0.0]) uses double precision:

double * array = (double *)data;
int length = size / sizeof(double);

The full example:

  • C++

    PyObject * MyFunction(PyObject * self, PyObject * args) {
        const char * data;
        int size;
    
        if (!PyArg_ParseTuple(args, "y#:MyFunction", &data, &size)) {
            return 0;
        }
    
        double * content = (double *)data;
        int length = size / sizeof(double);
    
        for (int i = 0; i < length; ++i) {
            double value = content[i];
    
            // ...
        }
    
        Py_RETURN_NONE;
    }
    
  • Python

    MyFunction(numpy.array([1.0, 2.0, 3.0]))
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.