'Convert numpy array to MemoryView object

I'm trying to convert a numpy array to a MemoryView object because I have to communicate between two programs. The one can only handle NumPy arrays and the other only MemoryView objects.

Converting from MemoryView to numpy array is easily done by:

import numpy as np
MyNumpyArray=np.array(MyMemoryView)

But how do you convert from numpy array to MemoryView?

I found here: https://docs.python.org/3/c-api/memoryview.html That there's a PyMemoryView_FromObject(PyObject *obj) function, but I don't know how to call it without an example.

Thanks!



Solution 1:[1]

Additionally to accepted answer providing another simple method to get memoryview out of Numpy array:

Try it online!

a = np.arange(1, 9)
view = a.data
print(type(view)) # <class 'memoryview'>

In other words .data attribute of array variable gives exactly memoryview.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1