codypiersall / pynng

Python bindings for Nanomsg Next Generation.
https://pynng.readthedocs.io
MIT License
268 stars 58 forks source link

Support for memoryview? #79

Open ZisIsNotZis opened 3 years ago

ZisIsNotZis commented 3 years ago

It would be nice to have memoryview supported to support zero-copying. Currently it seems that only bytes are supported which can't share memory with other objects

codypiersall commented 3 years ago

Do you mean for the methods Socket.send() and Socket.asend()? (and similarly for the pipe and context methods?) Or did you have something else in mind?

sk1p commented 2 years ago

It is possible to use a memoryview for sending - currently, you need to pierce through the abstraction and use the ffi instance from pynng in your user code, to convert it into an object that is understood by cffi. For example like this:

from pynng import ffi
import numpy as np

data = np.zeros(128)  # or whatever - just needs to support the buffer protocol
mv = memoryview(data)
your_socket.send(ffi.from_buffer(mv))

Maybe this could be directly supported in the send method, by wrapping the object to send into a from_buffer if it is a memoryview? Or even directly support objects that implement the buffer protocol, so one can directly call your_socket.send(some_numpy_array)