Of course it should be different!
When I used array1 = temp[:, 1]
, the array1 is not a real size (10,) ndarray. It is a view of the temp
, which is size(10, 2). Think about how it is stored in the memory - when the pointer go to another sizeof(double)
in c, it will encounter the next element in temp
, not in array1.
The way to fix it is - do not use ndarray view when reading your data! Use this line
array1 = temp[:, 1].copy()
to make a copy, instead of simply using the view.
The correct python code is:
import numpy as np
import ctypes
# wrap the function from dll to python
lib = ctypes.cdll.LoadLibrary('./testdll.dll')
fun = lib.copy_ndarray
fun.restype = None
fun.argtypes = [np.ctypeslib.ndpointer(ctypes.c_double), np.ctypeslib.ndpointer(ctypes.c_double), ctypes.c_size_t]
# Initialize array1 and array2
array_length= 10
temp = np.c_[100.*np.ones(array_length), 200.*np.ones(array_length)]
array1 = temp[:, 1].copy()
array2 = np.zeros(array_length)
fun(array1, array2, array_length)
I personally find this tricky, because as a data analyzer (honestly I'm not... I'm a researcher, but close enough!), 99% of the times a view is better than the copy, because it is faster, and we don't need the original ndarray once a data is read in anyways.
It is good to learn this and keep this in mind!