title: Dealing with problematic parent-child relationships enforced by C FFI
body: <p>I have a C library with an interface similar to this: (I have represented the C API within Rust, so that all of the code in this question can be concatenated in a single <code>.rs</code> file and easily tested)</p>
  
  <pre><code>// Opaque handles to C structs
  struct c_A {}
  struct c_B {}
  
  // These 2 `create` functions allocate some heap memory and other 
  // resources, so I have represented this using Boxes.
  extern "C" fn create_a() -&gt; *mut c_A {
      let a = Box::new(c_A {});
      Box::into_raw(a)
  }
  
  // This C FFI function frees some memory and other resources, 
  // so I have emulated that here.
  extern "C" fn destroy_a(a: *mut c_A) {
      let _a: Box&lt;c_A&gt; = unsafe { Box::from_raw(a) };
  }
  
  extern "C" fn create_b(_a: *mut c_A) -&gt; *mut c_B {
      let b = Box::new(c_B {});
      Box::into_raw(b)
  }
  
  // Note: While unused here, the argument `_a` is actually used in 
  // the C library, so I cannot remove it. (Also, I don't control 
  // the C interface)
  extern "C" fn destroy_b(_a: *mut c_A, b: *mut c_B) {
      let _b = unsafe { Box::from_raw(b) };
  }
  </code></pre>
  
  <p>I have created the following Rusty abstraction over the C functions:</p>
  
  <pre><code>struct A {
      a_ptr: *mut c_A,
  }
  
  impl A {
      fn new() -&gt; A {
          A { a_ptr: create_a() }
      }
  }
  
  impl Drop for A {
      fn drop(&amp;mut self) {
          destroy_a(self.a_ptr);
      }
  }
  
  struct B&lt;'a&gt; {
      b_ptr: *mut c_B,
      a: &amp;'a A,
  }
  
  impl&lt;'a&gt; B&lt;'a&gt; {
      fn new(a: &amp;'a A) -&gt; B {
          B {
              b_ptr: create_b(a.a_ptr),
              a,
          }
      }
  }
  
  impl&lt;'a&gt; Drop for B&lt;'a&gt; {
      fn drop(&amp;mut self) {
          destroy_b(self.a.a_ptr, self.b_ptr);
      }
  }
  </code></pre>
  
  <p>The <code>B</code> struct contains a reference to <code>A</code> for the sole reason that the <code>a_ptr</code> is necessary when calling the <code>destroy_b</code> function for memory cleanup. This reference is not needed by me for any of my Rust code.</p>
  
  <p>I would now like to create the following struct which references both A and B:</p>
  
  <pre><code>struct C&lt;'b&gt; {
      a: A,
      b: B&lt;'b&gt;,
  }
  
  impl&lt;'b&gt; C&lt;'b&gt; {
      fn new() -&gt; C&lt;'b&gt; {
          let a = A::new();
          let b = B::new(&amp;a);
          C { a, b }
      }
  }
  
  // Main function just so it compiles
  fn main() {
      let c = C::new();
  }
  </code></pre>
  
  <p>However, this will not compile:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0597]: `a` does not live long enough
    --&gt; src/main.rs:76:25
     |
  76 |         let b = B::new(&amp;a);
     |                         ^ borrowed value does not live long enough
  77 |         C { a, b }
  78 |     }
     |     - borrowed value only lives until here
     |
  note: borrowed value must be valid for the lifetime 'b as defined on the impl at 73:1...
    --&gt; src/main.rs:73:1
     |
  73 | impl&lt;'b&gt; C&lt;'b&gt; {
     | ^^^^^^^^^^^^^^
  </code></pre>
  
  <p>I understand why this fails: When returning the <code>C</code> struct from <code>C::new()</code>, it moves the <code>C</code>. This means that the <code>A</code> contained within is moved, which renders all references to it invalid. Therefore, there's no way I could create that <code>C</code> struct. (<a href="https://stackoverflow.com/a/32300133/2364686">Explained in much more detail here</a>)</p>
  
  <p>How can I refactor this code in such a way that I can store a <code>B</code> in a struct along with its "parent" <code>A</code>? There's a few options I've thought of, that won't work:</p>
  
  <ul>
  <li>Change the C interface: I don't control the C interface, so I can't change it.</li>
  <li>Have <code>B</code> store a <code>*mut c_A</code> instead of <code>&amp;A</code>: If <code>A</code> is dropped, then that raw pointer becomes invalid, and will result in undefined behavior when <code>B</code> is dropped.</li>
  <li>Have <code>B</code> store an owned <code>A</code> rather than a reference <code>&amp;A</code>: For my use case, I need to be able to create multiple <code>B</code>s for each <code>A</code>. If <code>B</code> owns <code>A</code>, then each <code>A</code> can only be used to create one <code>B</code>.</li>
  <li>Have <code>A</code> own all instances of <code>B</code>, and only return references to <code>B</code> when creating a new <code>B</code>: This has the problem that <code>B</code>s will accumulate over time until the <code>A</code> is dropped, using up more memory than necessary. However, if this is indeed the best way to go about it, I can deal with the slight inconvenience.</li>
  <li>Use the <a href="https://crates.io/crates/rental" rel="nofollow noreferrer"><code>rental</code></a> crate: I would rather take the slight memory usage hit than add the complexity of a new macro to my code. (That is, the complexity of anyone reading my code needing to learn how this macro works)</li>
  </ul>
  
  <p>I suspect that the best solution somehow involves storing at least <code>A</code> on the heap so it doesn't need to move around, but I can't figure out how to make this work. Also, I wonder if there is something clever that I can do using raw pointers.</p>