Search code examples
arraysnumpymemoryview

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

  • memoryview is one of the built-in types and can simply be called as:

    arr = np.random.rand(5,4)
    view = memoryview(arr)
    view
    <memory at 0x12699c318>