Convert numpy array to MemoryView object
Asked Answered
K

2

5

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!

Kotz answered 11/1, 2018 at 18:14 Comment(2)
Is the other program a C program? If it's Python, you can just use memoryview(np.array(...)).Astro
@AlexanderReynolds I think it is yeah, I'm talking to the GUI but I think it's C-based. Your solution and that of Grr worked as a charm! Strange that I couldn't find this simple solution online..Kotz
E
11

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>
Eschar answered 11/1, 2018 at 19:30 Comment(1)
Also view[i] can be used to index the memoryview object.Astro
W
6

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.

Whine answered 13/1, 2021 at 10:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.