Reputation: 157
Cython how to make multidimensional string matrix?any one knows?Thanks I have below code but not work:
def make_matrix(size_t nrows, size_t ncols):
cdef char *mat = <char*>malloc(nrows * ncols * sizeof(char))
cdef char[:, ::1] mv = <char[:nrows, :ncols]>mat
cdef cnp.ndarray arr = np.asarray(mv)
return arr
Upvotes: 1
Views: 115
Reputation: 30884
Given you want an array nrows
strings, each ncols
long you can just do:
np.zeros((nrows,),dtype=('S',ncols))
This creates an empty numpy array of the format you want, and there's no need to invoke specialised Cython features.
The good reason not to attempt to do it in Cython using malloc
is that the memory will never get freed (so you'll have a memory leak unless you free the memory yourself). It's very hard to know when you need to free it.
As an alternative (if you genuinely do need malloc
for some reason) you could work with int8
instead, which is the same size as a char
and should be interconvertable.
Upvotes: 1