Enforcing in-memory transposition of a numpy array

Viewed 494

I am interfacing a C library with python. I have arrays in numpy that I pass to the library using the ctypes attribute of the array.

At some point I need to provide an array to the C library, that is expected to be the transposed of the numpy array a I have. (Another way of putting it is that the C library does not accept a stride for the inner-most dimension). However when I pass a.T instead of a, nothing happens.

Indeed it seems that numpy does some sort of lazy transposition by simply swapping the strides:

import ctypes
import numpy as np
a = np.zeros((2, 3))
a.ctypes.strides_as(ctypes.c_longlong)[:]
# returns [24, 8]
a.T.ctypes.strides_as(ctypes.c_longlong)[:]
# return [8, 24]

My question is, how to enforce this transposition to happen in memory?

EDIT

I noticed that

a.T + np.zeros(a.T.shape)

reorders the memory like I want, but if there is a more elegant and explicit solution, I would still like to hear it.

(Also, interestingly,

a.T + np.zeros_like(a.T)

seems to not reorder memory).

1 Answers
Related