Return data from struct using Numpy Array
<p>I am writing Python C-extensions to a library and wish to return data as an Numpy Array.  The library has a function that returns data from a sensor into a C structure.  I would like to take the data from that structure and return it as a Numpy Array.</p>

<p>The structure definition in the library:</p>

<pre><code>typedef struct rs_extrinsics
{
    float rotation[9];    /* column-major 3x3 rotation matrix */
    float translation[3]; /* 3 element translation vector, in meters */
} rs_extrinsics;
</code></pre>

<p>The function prototype:</p>

<pre><code>void rs_get_device_extrinsics(const rs_device * device, rs_stream from_stream, rs_stream to_stream, rs_extrinsics * extrin, rs_error ** error);
</code></pre>

<p>Here is my code that is just trying to return the first value for now:</p>

<pre><code>static PyObject *get_device_extrinsics(PyObject *self, PyObject *args)
{
    PyArrayObject *result;
    int dimensions = 12;

    rs_stream from_stream;
    rs_stream to_stream;
    rs_extrinsics extrin;
    if (!PyArg_ParseTuple(args, "iiffffffffffff", &amp;from_stream, &amp;to_stream, &amp;extrin)) {
        return NULL;
    }

    result = (PyArrayObject *) PyArray_FromDims(1, &amp;dimensions, PyArray_DOUBLE);
    if (result == NULL) {
        return NULL;
    }

    rs_get_device_extrinsics(dev, from_stream, to_stream, &amp;extrin, &amp;e);
    check_error();
    result[0] = extrin.rotation[0];
    return PyArray_Return(result);
}
</code></pre>

<p>I get the following error on compile:</p>

<pre><code>error: assigning to 'PyArrayObject' (aka 'struct tagPyArrayObject_fields') from incompatible type 'float'
result[0] = extrin.rotation[0];
          ^ ~~~~~~~~~~~~~~~~~~
</code></pre>

<p>PyArrayObject, apart from data, have multiple fields:</p>

<pre><code>typedef struct PyArrayObject {
    PyObject_HEAD
    char *data;
    int nd;
    npy_intp *dimensions;
    npy_intp *strides;
    PyObject *base;
    PyArray_Descr *descr;
    int flags;
    PyObject *weakreflist;
} PyArrayObject;
</code></pre>

<p>You should get your data field data from your PyArrayObjects. Like this: <code>result-&gt;data[index];</code>  Also you need to cast your data to proper type indicated by <code>result-&gt;descr-&gt;type</code> character code. Also dims, you are passing to PyArray constructor should be of type <code>npy_intp *</code>, not int. Type of array in your case should be <code>NPY_DOUBLE</code>.</p>

<p>If you are calling your function from python (are you?), you better just passing list object from Python and use PyList C API to manage float sequence. </p>

<pre><code>PyObject*list_of_floats;
PyArg_ParseTuple(args, "iiO", &amp;from_stream, &amp;to_stream, &amp;list_of_floats);
</code></pre>

python c arrays numpy python-c-extension