mpiccolo
mpiccolo

Reputation: 672

Rust Vec to Ruby Array with FFI Segfaults

I am trying to return a struct that can be converted into a Ruby array from an external rust function but when I try to call the structs #to_a method I get a segfault.

use libc::size_t;
#[repr(C)]
pub struct Array {
    len: libc::size_t,
    data: *const libc::c_void,
}

impl Array {
    fn from_vec<T>(mut vec: Vec<T>) -> Array {

        vec.shrink_to_fit();

        let array = Array { data: vec.as_ptr() as *const libc::c_void, len: vec.len() as libc::size_t };

        mem::forget(vec);

        array
    }
}

#[no_mangle]
pub extern fn get_links(url: *const libc::c_char) -> Array {

  // Get links

  let mut urls: Vec<String> = vec![];

  // push strings into urls vec

  // urls => collections::vec::Vec<collections::string::String>

  Array::from_vec(urls)
}
require 'ffi'

module Rust
  extend FFI::Library
  ffi_lib './bin/libembed.dylib'

  class NodesArray < FFI::Struct
      layout :len,    :size_t, # dynamic array layout
             :data,   :pointer #

      def to_a
          self[:data].get_array_of_string(0, self[:len]).compact
      end
  end

  attach_function :get_links, [:string], NodesArray.by_value
end

When I try to use this function in ruby it will return the Fii::NodesArray. I can also get the len and data off of the struct. It is only when I call the #to_a that segfaults.

Upvotes: 3

Views: 614

Answers (2)

mpiccolo
mpiccolo

Reputation: 672

The issue, pointed out by Adrian, was that I was pushing strings into the Vec. FFI needs *const libc::c_char, which can be converted from a String.

let mut urls: Vec<*const libc::c_char> = vec![];

urls.push(CString::new(string_var.value.to_string()).unwrap().into_raw());

Upvotes: 2

Adrian
Adrian

Reputation: 15171

It seems like FFI::Pointer#get_array_of_string is bugged (or it just doesn't do what I think it does). Your code works for me if I change this line:

self[:data].get_array_of_string(0, self[:len]).compact

to this:

Array.new(self[:len]) {|i| self[:data].read_pointer[i * FFI::Pointer::SIZE].read_string }

Upvotes: 1

Related Questions