title: The best way in Rust to return a dynamic string from extern "C" method to be consumed by C or C++
body: <p><em>This one is somewhat relevant, but the answer is not really clear for me:
  <a href="https://stackoverflow.com/questions/28866103/c-library-freeing-a-pointer-coming-from-rust">C library freeing a pointer coming from Rust</a></em></p>
  
  <p>There's also an <a href="https://doc.rust-lang.org/book/ffi.html#calling-rust-code-from-c" rel="nofollow noreferrer">example with static string</a> in the book, however it would not properly work with the dynamically created string.</p>
  
  <p>I came to this solution finally where calling C/C++ code allocates and later deallocates memory for the string to be received, but it looks somewhat ugly and has to define some particular length for unknown string:</p>
  
  <pre><code>#[no_mangle]
  pub extern fn rs_string_in_string_out(s_raw: *const c_char, out: *mut c_char) -&gt; c_int {
      // take string from the input C string
      if s_raw.is_null() { return 0; }
  
      let c_str: &amp;CStr = unsafe { CStr::from_ptr(s_raw) };
      let buf: &amp;[u8] = c_str.to_bytes();
      let str_slice: &amp;str = std::str::from_utf8(buf).unwrap();
      let str_buf: String = str_slice.to_owned();
  
      //produce a new string
      let result = String::from(str_buf + " append from Rust");
      let len = result.len();
  
      //create C string for output
      let c_result = CString::new(result);
  
      //write string into out pointer passed by C++ addon
      unsafe{ std::ptr::copy(c_result.unwrap().as_ptr(), out, len); };
  
      // return result length
      return len as c_int;
  }
  </code></pre>
  
  <p>It would be nice to have somewhat that actually returns a value, rather than writing into mutable argument.</p>