Creating an array of numpy custom class objects with C API

Using the C API, I would like to create a numpy array containing objects of type Quaternionthat is a class written in C ++. I already have an array of them (actually a std::vector), and I want to make a copy - or use the same memory, if possible.

Since this is not a basic type, I need to use types Py_Objectand cannot use PyArray_SimpleNeweither something simple.

I suppose I could use PyArray_NewFromDescror even PyArray_SimpleNewFromDescr, but I completely and completely lost how to create the object PyArray_Descrthat I need to describe for my Quaternion class.

Can someone give me some guidance on how to make this descr object? Or give me a better idea on how to build my numpy array?

This is basically a more general version of this question , without distractions.

EDIT:

Using the dastrobu hint and my SWIG shell, I found a way to do this. I know that not everyone uses SWIG, but for those who are, my answer on my other question shows how I handled this.

+4
source share
1 answer

Quaternion , numpy.object dtype. , PyArray_SimpleNew(..., NPY_OBJECT) . , Quaternion python. Quaternion . ( , , , python?) Quaternion - PyQuaternion. . :

typedef struct {
    PyObject_HEAD
    Quaternion *q;
}PyQuaternion;

static PyTypeObject PyQuaternion_Type = {
    PyObject_HEAD_INIT(NULL)
    0,                                        /*ob_size*/
    "Quaternion",                             /*tp_name*/
    sizeof(PyQuaternion),                     /*tp_basicsize*/
/* ... */
};


static PyObject *
PyQuaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds){
/* ... */
};

static int 
PyQuaternion_init(PyQuaternion *self, PyObject *args, PyObject *kwds){
/* ... */
};

static void PyQuaternion_dealloc(PyQuaternion *self){
/* ... */
};

, C-API PyQuaternionType, PyQuaternions Quaternions

static PyObject *
PyQuaternion_New(Quaternion *q){
    PyQuaternion *self;
    self = (PyQuaternion *)PyQuaternion_Type.tp_new(type, NULL, NULL);
    self->q = q; 
    return (PyObject *)self;
}

, self->q PyQuaternion_dealloc, . - PyQuaternion_dealloc self->q.

PyQuaternion_New Quaternion python, , , , , numpy dtype = numpy.object.

+3

All Articles