title: Calling Rust from Swift
body: <p>On the Rust side I wrote a function that returns a String as a pointer of bytes (laid out in memory as a C struct):</p>
  
  <pre><code>#[repr(C)]
  pub struct RustByteSlice {
      pub bytes: *const u8,
      pub len: size_t,
  }
  
  #[no_mangle]
  pub extern "C" fn get_string_from_rust() -&gt; RustByteSlice {
      let s = "This is a string from Rust.";
      RustByteSlice {
          bytes: s.as_ptr(),
          len: s.len() as size_t,
      }
  }
  </code></pre>
  
  <p>When generating a header file for it using cbindgen it gives me the following output:</p>
  
  <pre><code>#include &lt;stdarg.h&gt;
  #include &lt;stdbool.h&gt;
  #include &lt;stdint.h&gt;
  #include &lt;stdlib.h&gt;
  
  typedef struct {
    const uint8_t *bytes;
    size_t len;
  } RustByteSlice;
  
  RustByteSlice get_string_from_rust(void);
  
  char *hello(const char *to);
  
  void hello_release(char *s);
  
  void utf8_bytes_to_rust(const uint8_t *bytes, size_t len);
  </code></pre>
  
  <p>In my Xcode project, this header is used as the bridging header, and the shared library compiled from the rust code is added to the dependency list. The header and include folders are defined in the build properties.</p>
  
  <p>On the swift side I'm calling the rust function the following way:</p>
  
  <pre><code>struct RustByteSlice {
      var bytes: UnsafePointer&lt;UInt8&gt;
      var len: Int
  
      func asUnsafeBufferPointer() -&gt; UnsafeBufferPointer&lt;UInt8&gt; {
          return UnsafeBufferPointer(start: bytes, count: len)
      }
      func asString(encoding: String.Encoding = String.Encoding.utf8) -&gt; String? {
          return String(bytes: asUnsafeBufferPointer(), encoding: encoding)
      }
  }
  
  func strPtrRet() {
      let rustString: RustByteSlice = get_string_from_rust()
  
      if let stringFromRust = rustString.asString() {
          print("got a string from Rust: (stringFromRust)")
      } else {
          print("Could not parse Rust string as UTF-8")
      }
  }
  </code></pre>
  
  <p>On the line <code>let rustString: RustByteSlice = get_string_from_rust()</code>, I get the following error:</p>
  
  <pre><code>Cannot convert value of type '__ObjC.RustByteSlice' to specified type 'ed25_ios_app.RustByteSlice'
  </code></pre>
  
  <p>How can I solve or work around this error ?</p>