像NumPy这样的库的底层是用C写的,如果想要从底层修改NumPy库,就要熟悉PyObject和PyArrayObject的取值和赋值方法。
C和Python之间的交互
如何查看PyArrayObject的属性
PyArrayObject* ret;
printf("type=%d\n",PyArray_TYPE(ret));//类型
printf("ndim=%d\n",PyArray_NDIM(ret));//维度
printf("size=%d\n",PyArray_SIZE(ret));//大小
printf("shape[0]=%d\n",PyArray_SHAPE(ret)[0]);
long *pd = PyArray_DATA(ret);
printf("long ret= %ld\n", *pd);//值
如何查看PyObject的属性
//以查看key的type为例
PyObject* key;
PyTypeObject* type = key->ob_type;
const char* p = type->tp_name;
std::cout << "My type is " << p << std::endl;
//从PyObject里取值,需要看PyObject的type采用对应的函数
//PyLong_AsDouble,PyFloat_AsDouble之类的有很多
PyObject *pValue;
int res=PyInt_AsLong(pValue);
printf("res=%d\n",res);
向PyArrayObject的元素赋值
方法一:操纵指针赋值
PyArrayObject* rp;
//tmp是你想赋值的元素数组和类型
int tmp[1];
tmp[0]=1;
int* rptr = (int *)PyArray_DATA(rp);
*rptr=tmp[0];
方法二:新生成一个PyArrayObject
PyArrayObject* ret;
//tmp是你想赋值的元素数组和类型
int tmp[1];
tmp[0]=1;
int Dims[1];
Dims[0] = 1;
ret=(PyArrayObject *)PyArray_SimpleNewFromData(0,Dims,int,tmp);