C Contiguous Array in PyCall

Hey everyone,

I am trying to communicate with a National Instrument DAQ via PyCall.jl and the NI Python library nidaqmx. For some functions I have to pass a C contiguous array (flag C_CONTIGUOUS has to be true).

I tried to create a C contiguous array using PyCall and np.ascontiguousarray but the C_CONTIGUOUS flag stays false. Here is my minimal working example:

using PyCall
np = pyimport("numpy")
nidaqmx = pyimport("nidaqmx")


data = ones(10)
dataMatrix = repeat(reshape(data, 1, :), 2, 1)

dataMatrix_np = PyObject(np.ascontiguousarray(np.array(dataMatrix, dtype=np.float64, copy=true)))

println("Data matrix flags: $(dataMatrix_np.flags)")

This results in:

Data matrix flags: PyObject   C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False

I would be very thankful for any advice on this!
Frauke

Actually, I found a related post and this does the trick:

using PyCall
np = pyimport("numpy")
nidaqmx = pyimport("nidaqmx")


data = ones(10)
dataMatrix = repeat(reshape(data, 1, :), 2, 1)

dataMatrix_np = PyReverseDims(dataMatrix)

println("Data matrix flags: $(dataMatrix_np.flags)")

Here is the link to the post:

1 Like

If you’re fine with switching to PythonCall.jl, which does not automatically convert a NumPy array into an Array, you could alternatively just use

dataMatrix_np = np.ascontiguousarray(np.array(dataMatrix, dtype=np.float64, copy=true))
# type is Py, while for PyCall this would be Matrix{Float64}

or simply

dataMatrix_np = np.array(dataMatrix, dtype=np.float64, copy=true, order="C")

If you want to convert back to a Julia ::AbstractArray, you can use PyArray(dataMatrix_np)/pyconvert(PyArray, dataMatrix_np) (wraps, row-major) or pyconvert(Array, dataMatrix_np) (copies, column-major).

2 Likes