tuffy
July 29, 2020, 6:10pm
1
Using the latest PyO3, given some function which returns a bunch of bytes, like:
#[pyfunction]
fn some_bytes() -> Vec<u8> {
vec[1,2,3]
}
When called on the Python side, it returns a list of integers, like:
>>> some_bytes()
[1, 2, 3]
What's the most straightforward way to have the function return a (binary) bytes object? Like:
>>> some_bytes()
b'\x01\x02\x03'
It seems like it should be a trivial conversion, but I've just started with PyO3 and the documentation has me stumped. Any help would be appreciated!
s3bk
July 30, 2020, 10:08am
2
I guess you have to explicit about the Python side type:
use pyo3::types::PyBytes;
#[pyfunction]
fn some_bytes(py: Python) -> PyBytes {
let data = vec![1, 2, 3];
PyBytes::new(py, &data)
}
1 Like
tuffy
July 30, 2020, 1:12pm
3
That one almost works, but it's definitely a step in the right direction. Turns out the compiler doesn't like PyBytes
as a return type, but a slight adjustment:
use pyo3::types::PyBytes;
#[pyfunction]
fn some_bytes(py: Python) -> PyObject {
let data = vec![1, 2, 3];
PyBytes::new(py, &data).into()
}
compiles properly and works as expected.
Thanks!
2 Likes
system
Closed
October 28, 2020, 1:12pm
4
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.