Re: [cython-users] Can only create cython.array from pointer or array

96 views
Skip to first unread message

Stefan Behnel

unread,
Nov 24, 2017, 2:41:39 AM11/24/17
to cython...@googlegroups.com
Zahra Sheikh schrieb am 21.11.2017 um 21:47:
> I am trying to assign a dynamic c-array to a memoryview. Using Matrix
> class, I want to assign a pointer array to a memoryview:
>
> import numpy as np
> cimport numpy as np
> from numpy import int32
> from numpy cimport int32_t
> from cython.view cimport array as cvarray
> from libc.stdlib cimport malloc, free
> from libc.math cimport log, exp
> from cython cimport boundscheck, wraparound
> cdef extern from "gsl/gsl_rng.h":
> ctypedef struct gsl_rng_type
> ctypedef struct gsl_rng
> gsl_rng_type *gsl_rng_mt19937
> gsl_rng *gsl_rng_alloc(gsl_rng_type * T) nogil
> void gsl_rng_set(gsl_rng *r, unsigned long int s)
>
> cdef extern from "gsl/gsl_randist.h" nogil:
> double gamma "gsl_ran_gamma"(gsl_rng * r, double, double)
> unsigned int bernoulli "gsl_ran_bernoulli"(gsl_rng * r, double)
> double beta "gsl_ran_beta"(gsl_rng * r, double, double)
>
> cdef gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937)
>
> *cdef class Matrix: cdef int32_t *data cdef public int n_ax0,
> n_ax1 def __init__(self, int n_ax0, int n_ax1): self.data =
> <int32_t*> malloc (sizeof(int32_t) * n_ax0 * n_ax1) self.n_ax0 =
> n_ax0 self.n_ax1 = n_ax1 def __dealloc__(self):
> free(self.data)*
> cdef double[::1] _generate(double alpha,int number) nogil:
> cdef double[::1] mu = cvarray(shape=(number,),
> itemsize=sizeof(double), format='d')
> cdef Py_ssize_t i
> for i from 0 <= i <number:
> mu[i]=beta(r, alpha, 1)
> return mu
>
> @boundscheck(False)
> @wraparound(False)
> cdef int32_t[:,::1] _initial(double alpha, int N, int D):
>
> *cdef Matrix arr = Matrix(N,D) cdef int32_t[:,::1] Z =
> <int32_t[:N,:D]>arr *
> cdef double[::1] mu = _generate(alpha,D)
> cdef Py_ssize_t i, j
> for i from 0 <= i < D:
> for j from 0 <= j < N:
> Z[j,i]= bernoulli(r, mu[i])
> return Z
>
> But I got this error message:
>
> Error compiling Cython file:
> ------------------------------
> ------------------------------
> ...
>
> @boundscheck(False)
> @wraparound(False)
> cdef int32_t[:,::1] _initial(double alpha, int N, int D):
> cdef Matrix arr = Matrix(N,D)
> cdef int32_t[:,::1] Z = <int32_t[:N,:D]>arr
> ^
> ------------------------------------------------------------
>
> test.pyx:55:49: Can only create cython.array from pointer or array
>
> What is the reason that this error occurs?

You should probably access "arr.data" here and not "arr". Or, implement the
buffer interface in the Matrix class, but that's more effort.

Stefan
Reply all
Reply to author
Forward
0 new messages