I'm trying to implement a Rust binding for a C library but now fall into a problem of pointer wrapping with callbacks.
First, to wrap the existing pointer of the library, I've used:
struct PtrWrapper<'a> {
ptr: u64, // raw pointer
callback: Callback<'a>, // callback which will use the raw pointer
}
where Callback
is parametrized by lifetime 'a
struct Callback<'a> {
pw: &'a PtrWrapper<'a>,
callback: Box<Fn(&'a PtrWrapper<'a>)>,
}
for which I want to mean the callback
inside would be called only by passing a pointer with lifetime the same as pw
(I think this design for safety: one can only pass a living pointer to the callback).
Until now, there isn't any problem yet. But when I implement a function update_callback
for PtrWrapper
as:
impl<'a> PtrWrapper<'a> {
pub fn update_callback(&mut self, F: impl Fn(&'a PtrWrapper<'a>)) {
let cb = Callback {
pw: self,
callback: Box::new(F),
};
self.callback = cb;
}
}
the compiler is not happy, I stuck with the error:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> src/main.rs:13:27
|
13 | let cb = Callback {
| ^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 12:5...
--> src/main.rs:12:5
|
12 | / pub fn update_callback(&mut self, F: impl Fn(&'a PtrWrapper<'a>, u64)) {
13 | | let cb = Callback {
14 | | pw: self,
15 | | callback: Box::new(F),
... |
18 | | self.callback = cb;
19 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:14:17
|
14 | pw: self,
| ^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 11:6...
--> src/main.rs:11:6
|
11 | impl<'a> PtrWrapper<'a> {
| ^^
= note: ...so that the expression is assignable:
expected &PtrWrapper<'_>
found &PtrWrapper<'a>
error: aborting due to previous error
For more information about this error, try `rustc --explain E0495`.
I guess that there is a conflict between the lifetime 'a
used in pub fn update_callback(&mut self, F: impl Fn(&'a PtrWrapper<'a>))
and the lifetime of self
, but still do not know how to fix.
Moreover,
rustc --explain E0495
error: no extended information for E0495
Many thanks for any help.