PyArray_SimpleNewFromData example

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

I know that this thing has been answered a lot of times and I have also read the documentation as well but still I am not able to clearly understand how is this working. As in, I am not able to understand how the values are populated in its arguments. The examples are not very clearly explaining it(or may be I am not able to). Can anyone please help me understand how are the arguments of this function populated? What should be their values? I have to pass a vector from C++ to Python without reallocating the memory. Any help is much appreciated. I am stuck on this from a lot of days.

My code which I am implementing:

回答1:

The function is:

 PyObject *     PyArray_SimpleNewFromData(         int nd,          npy_intp* dims,          int typenum,           void* data) 
  • The last argument (data) is a buffer to the data. Let's dispense with that.

  • The second argument (dims) is a buffer, whose each entry is a dimension; so for a 1d array, it could be a length-1 buffer (or even an integer, since each integer is a length-1 buffer)

  • Since the second argument is a buffer, the first argument (nd) tells its length

  • The third argument (typenum) indicates the type.


For example, say you have 4 64-bit ints at x:

To create an array, use

int dims[1]; dims[0] = 4; PyArray_SimpleNewFromData(1, dims, NPY_INT64, x) 

To create a 2X2 matrix, use

int dims[2]; dims[0] = dims[1] = 2; PyArray_SimpleNewFromData(2, dims, NPY_INT64, x) 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!