Passing opened files from Python to Rust #3153
-
|
Hi, I've got a Rust API exposed to Python (say It would be good if I could receive that reader as The problem is passing data that is potentially big but could be read sequentially on the Rust side. I've workarounded it by building special functions that pass filenames to Rust and then open the file in Rust but then I need to expose special functions for bytes etc. Is there a better way to do it? I've searched the issues but didn't get any useful results. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
|
I think there are two issues: Passing files and passing I/O objects like If you are able to avoid the Otherwise, you could just take struct PyReader<'a>(&'a PyAny);
impl Read for PyReader<'_> { ... }which would however imply quite a bit of overhead to copy the bytes return by the Python |
Beta Was this translation helpful? Give feedback.
-
|
After finding this discussion, I also found out that a few people made libraries to provide a convenient Rust wrapper. I like this one. |
Beta Was this translation helpful? Give feedback.
I think there are two issues: Passing files and passing I/O objects like
BufferedReader(which also manage an internal buffer).If you are able to avoid the
BufferedReaderlayer, you could pass file descriptors which are basically integers to Rust and useFile::from_raw_fd.Otherwise, you could just take
&PyAnyand assume that it has areadPython method which you can call viaPyAny::call1. You could then try to implement a custom wrapper likewhich would however imply quite a bit of overhead to copy the bytes return by the Python
readinto the&mut [u8]buffer passed into the Rustread.