rd11 rd11 - 1 year ago 145
C Question

What is the correct usage of PyArray_SIZE?

I'm new to manipulating numpy arrays in C. Here is a snippet of code that lets me 1) pass a list of 1-D, 64-bit-float numpy arrays to C and 2) loop through each array, printing its contents.

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include "Python.h"
#include "numpy/arrayobject.h"
#include "list_of_ndarrays_lib.h"

void print_all(PyObject *list) {

int i, j;
PyArrayObject *arrayObj;
double *arrayData;

for (i = 0; i < PyObject_Length(list); i++) {

arrayObj = (PyArrayObject *) PyList_GET_ITEM(list, i);

arrayData = PyArray_DATA(arrayObj);
for (j = 0; j < PyArray_SHAPE(arrayObj)[0]; j++) {
printf("%f ", arrayData[j]);



This code works, but
doesn't generalize to n-dimensional arrays, and if I replace it with
, I get a segmentation fault.

What am I doing wrong with

Answer Source

I think the problem here might be that all of the Py* functionality, including the PyArray* functionality, is at-your-own-risk unless you properly modify your code to become a C extension module.

A clear writeup on the subject is here. There is a little bit of boilerplate, but other than that, this method is pretty nice. No external dependencies (like Boost.Python), and it makes your Python code very clean, eliminating the need for specifying function signatures via ctypes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download