1

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 
0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.