title: How can I expose a safe wrapper around an owned pointer?
body: <p>I'm wrapping a C library that has two structs: one has a pointer to the other.</p>
  
  <pre><code>struct StructA {
      void * some_mem;
  };
  
  struct StructB {
      void * some_mem;
      struct StructA * some_struct;
  };
  </code></pre>
  
  <p>Both of these structs own memory, so my wrapper has constructors and destructors for both of them.</p>
  
  <pre><code>struct StructA(*mut c_void);
  
  impl StructA {
      fn new() -&gt; Self {
          StructA(c_constructor())
      }
  }
  
  impl Drop for StructA {
      fn drop(&amp;mut self) {
          let StructA(ptr) = self;
          c_destructor(ptr);
      }
  }
  </code></pre>
  
  <p>There's also a function that takes a pointer to <code>StructB</code> and returns its pointer to <code>StructA</code>:</p>
  
  <pre><code>const struct StructA * get_struct(const struct StructB * obj);
  </code></pre>
  
  <p>The user of this function should not free the returned pointer, since it will be freed when the user frees <code>obj</code>.</p>
  
  <p>How can I wrap this function? The problem is that the destructor for <code>StructB</code> frees all its memory, including the one for <code>StructA</code>. So if my wrapping of <code>get_struct</code> returns an object, then the wrapped <code>StructA</code> will be freed twice (right?). It could instead return a reference to an object, but where would that object live?</p>
  
  <p>I could have separate structs for <code>StructA</code> based on whether it's standalone and needs to be freed or if it's a reference, but I'm hoping that's unnecessary.</p>