Since Quaternion
不是直接的数字类型,你的数组必须有numpy.object
as 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-APIPyQuaternionType
让您能够创造PyQuaternions
from 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
.
The PyQuaternion_New
函数允许你换行Quaternion
对象并将它们填充到任何 python 容器中,例如列表、元组,当然还有 numpy 数组dtype = numpy.object
.