My program involves in reading data from data,
storing the data in a vec,
and use a struct to store the parsed result.
I want to avoid the copy the original data.
let file_data: Vec<u8> = ... // Read from file
use core::ffi::CStr;
struct Foo<'a> {
name: &'a CStr,
value: &'a [u8]
}
However, now I need to bind Foo
to Python,
so I need to use the pyo3
crate.
It requires that python class cannot have lifetime,
because python uses garbage collection and referencing counting to handle lifetime
struct Foo {
...
}
So what is the recommended approach to the remove 'a
lifetime?
I know that one way is to use self referencing type
/*
[dependencies]
ouroboros = "0.16"
*/
use ouroboros::self_referencing;
use core::ffi::CStr;
use std::sync::Arc;
#[self_referencing]
struct Foo {
file_data: Arc<Vec<u8>>,
#[borrows(file_data)]
// the 'this lifetime is created by the #[self_referencing] macro
// and should be used on all references marked by the #[borrows] macro
name: &'this CStr,
#[borrows(file_data)]
value: &'this [u8],
}
But this makes API very complicated,
and many extra code needed to construct the struct,
and parsing code need to be redesigned
and I have roughly 10 similar structs
Any suggestions?