Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Calling Rust from other languages

Calling Rust from other languages

My lightning talk at PolyConf 2015.

Zbigniew Siciarz

July 02, 2015
Tweet

More Decks by Zbigniew Siciarz

Other Decks in Programming

Transcript

  1. fn rust_substrings(value: &str, substr: &str) -> i32 { let mut

    count = 0; let substr_len = substr.len(); let upper_bound = value.len() - substr_len + 1; for c in 0..upper_bound { let possible_match = &value[c..c+substr_len]; if possible_match == substr { count += 1; } } count } Zbigniew Siciarz @zsiciarz siciarz.net
  2. #[no_mangle] pub extern "C" fn count_substrings( value: *const c_char, substr:

    *const c_char) -> i32 { let c_value = unsafe { CStr::from_ptr(value).to_bytes() }; let c_substr = unsafe { CStr::from_ptr(substr).to_bytes() }; match str::from_utf8(c_value) { Ok(value) => match str::from_utf8(c_substr) { Ok(substr) => rust_substrings(value, substr), Err(_) => -1, }, Err(_) => -1, } } Zbigniew Siciarz @zsiciarz siciarz.net
  3. #include <stdint.h> #include <stdio.h> int32_t count_substrings(const char* value, const char*

    substr); int main() { printf("%d\n", count_substrings("banana", "na")); return 0; }s Zbigniew Siciarz @zsiciarz siciarz.net
  4. require 'ffi' module StringTools extend FFI::Library ffi_lib "../target/debug/libstringtools.so" attach_function :count_substrings,

    [:string, :string], :int end puts StringTools.count_substrings("banana", "na") Zbigniew Siciarz @zsiciarz siciarz.net
  5. using System; using System.Runtime.InteropServices; public class StringTools { [DllImport("../target/debug/libstringtools.so")] public

    static extern Int32 count_substrings(string value, string substr); static public void Main() { Console.WriteLine(count_substrings("banana", "na")); } } Zbigniew Siciarz @zsiciarz siciarz.net
  6. {-# LANGUAGE ForeignFunctionInterface #-} import Foreign.C.String (CString, newCString) foreign import

    ccall "count_substrings" count_substrings :: CString -> CString -> IO Int main :: IO () main = do value <- newCString "banana" substr <- newCString "na" count_substrings value substr >>= print Zbigniew Siciarz @zsiciarz siciarz.net
  7. package main // #cgo LDFLAGS: -L../target/debug -lstringtools // int count_substrings(const

    char* value, const char* substr); import "C" import "fmt" func main() { value := C.CString("banana") substr := C.CString("na") fmt.Println(C.count_substrings(value, substr)) } Zbigniew Siciarz @zsiciarz siciarz.net