Guest User

PyArray_NewFromDescr Example

a guest
May 22nd, 2018
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. import numpy as np
  2.  
  3. cimport numpy as np
  4. np.import_array()
  5.  
  6. from libc.stdlib cimport malloc, calloc, free
  7. from cpython.ref cimport PyTypeObject
  8. from python_ref cimport Py_INCREF
  9.  
  10. cdef extern from "<numpy/arrayobject.h>":
  11.     object PyArray_NewFromDescr(PyTypeObject *subtype, np.dtype descr,int nd, np.npy_intp* dims,
  12.             np.npy_intp*strides,void* data, int flags, object obj)
  13.  
  14.  
  15. def stackarr():
  16.     cdef np.npy_intp dims[2]
  17.     #cdef np.npy_intp strides[2]
  18.     #cdef char *data
  19.     #data = <char *>calloc(100, sizeof(char))
  20.  
  21.     cdef float *data
  22.     data = <float *>calloc(100, sizeof(float))
  23.  
  24.     cdef np.dtype dtype = np.dtype('<f')
  25.     Py_INCREF(dtype)
  26.  
  27.  
  28.     dims[0] = 10
  29.     dims[1] = 10
  30.     #strides[0] = 1
  31.     #strides[1] = 10
  32.     for i in range(10):
  33.         for j in range(10):
  34.             data[i * 10 + j] = i * 10 + j
  35.    
  36.     ret = PyArray_NewFromDescr(<PyTypeObject *> np.ndarray, np.dtype('<f'), 2,
  37.             dims, NULL,data, np.NPY_C_CONTIGUOUS, None)
  38.     return ret
  39.  
  40. print "Successfully imported"
Add Comment
Please, Sign In to add comment