ich Einwickeln einer C-Bibliothek, und es hat eine Standard-Art von Kontextobjekt:Beschränken Objektlebensdauern in Rust
library_context* context = library_create_context();
Und dann mit, dass Sie mehrere Objekte erstellen:
library_object* object = library_create_object(context);
und zerstören sie beide:
library_destroy_object(object);
library_destroy_context(context);
Also habe ich diese structs in Rust verpackt:
struct Context {
raw_context: *mut library_context,
}
impl Context {
fn new() -> Context {
Context {
raw_context: unsafe { library_create_context() },
}
}
fn create_object(&mut self) -> Object {
Object {
raw_object: unsafe { library_create_object(self.raw_context) },
}
}
}
impl Drop for Context {
fn drop(&mut self) {
unsafe {
library_context_destroy(self.raw_context);
}
}
}
struct Object {
raw_object: *mut library_object,
}
impl Drop for Object {
fn drop(&mut self) {
unsafe {
library_object_destroy(self.raw_object);
}
}
}
So, jetzt kann ich dies tun, und es scheint zu funktionieren:
fn main() {
let mut ctx = Context::new();
let ob = ctx.create_object();
}
Allerdings kann ich auch dies tun:
fn main() {
let mut ctx = Context::new();
let ob = ctx.create_object();
drop(ctx);
do_something_with(ob);
}
D.h. Der Bibliothekskontext wird zerstört, bevor die Objekte erstellt werden.
Kann ich irgendwie das Lebenszeit-System von Rust verwenden, um zu verhindern, dass der obige Code kompiliert wird?
Bitte erstellen Sie ein [MCVE], wenn Sie Fragen stellen. Der angegebene Code schlägt mit 7 Fehlern nicht definierter Elemente fehl. Es ist auch möglich, dass du mehr ** M ** machen kannst, während du es ** C ** machst. – Shepmaster