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!

2
  • Is the other program a C program? If it's Python, you can just use memoryview(np.array(...)). Commented Jan 11, 2018 at 18:39
  • @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.. Commented Jan 11, 2018 at 21:40

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Also view[i] can be used to index the memoryview object.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.