Conceptual
Login

Handing Ownership to C with ForeignOwnable

When you register with a bus or open a device file, C stores one pointer-sized value for you and gives it back on every later callback. ForeignOwnable is the trait that converts an owned Rust value, typically a box or a reference-counted handle, into that raw pointer and back again without leaking the ownership. Going out turns the value into a pointer and forgets it on the Rust side; coming back reconstitutes exactly the same owner, so Drop still runs at the right moment. The C equivalent is the private-data pointer that everybody stores and half of us forget to free.

Questions this Concept answers

  • Why must converting a Rust value into its foreign representation forget the value on the Rust side?

This Concept is waiting for its first lesson!

When you register with a bus or open a device file, C stores one pointer-sized value for you and gives it back on every later callback. ForeignOwnable is the trait that converts an owned Rust value, typically a box or a reference-counted handle, into that raw pointer and back again without leaking the ownership. Going out turns the value into a pointer and forgets it on the Rust side; coming back reconstitutes exactly the same owner, so Drop still runs at the right moment. The C equivalent is the private-data pointer that everybody stores and half of us forget to free.

Are you a teacher? Sign in to start contributing.

Sign In