title: Returning array from Rust to FFI
body: <p>I need to write a function that returns array of u16 integers in Rust. This function then should be used by FFI.</p>
  
  <pre class="lang-rust prettyprint-override"><code>extern crate libc;
  use libc::{uint16_t};
  
  #[no_mangle]
  pub extern fn ffi_test() -&gt;  *const uint16_t {
      let test: [u16;4] = [1,2,3,4];
  
      test.as_ptr()
  }
  </code></pre>
  
  <p>Rust code compiles without errors. I used Ruby to test the ffi call:</p>
  
  <pre class="lang-rb prettyprint-override"><code># coding: utf-8
  require 'ffi'
  
  module MyMod
    extend FFI::Library
    ffi_lib 'my_ffi_test_lib'
    attach_function :ffi_test, [], :pointer
  end
  
  a_ptr = MyMod.ffi_test
  size = 4
  result_array = a_ptr.read_array_of_uint16(size)
  p result_array
  </code></pre>
  
  <p>But the results are totally wrong (expected: <code>[1, 2, 3, 4]</code>):</p>
  
  <pre><code>$ ruby ffi_test.rb
  [57871, 25191, 32767, 0]
  </code></pre>
  
  <p>As if I am reading totally diffirent memory addr. I assume maybe that I should not use <code>#as_ptr()</code> on Rust array?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>As per recommendation of @FrenchBoiethios I tried to box the array:</p>
  
  <pre class="lang-rust prettyprint-override"><code>extern crate libc;
  use libc::{uint16_t};
  
  #[no_mangle]
  pub extern fn ffi_test() -&gt;  *mut uint16_t {
      let test: [u16;4] = [1,2,3,4];
  
      let b = Box::new(test);
      Box::into_raw(b)
  }
  </code></pre>
  
  <p>This gives compile error:</p>
  
  <pre><code>note: expected type `std::boxed::Box&lt;u16&gt;`
           found type `std::boxed::Box&lt;[u16; 4]&gt;`
  </code></pre>