Racket to Rust
For a small project I was working on, I was looking at Racket to Rust FFI. There’s enough relevant documentation for both languages respective FFI interfaces, but when I first started googling, the only example post I saw was from 2013: Embedding Rust in Racket by John Clements.
Unsurprisingly the racket hasn’t changed, but the rust used in the article is no-longer valid.
If you wanted an example simpler example of FFI valid for current rust, you could use this:
#lang racket
(require ffi/unsafe
ffi/cvector
ffi/unsafe/define)
;; Define the C types we will use
(define rust-lib (ffi-lib (build-path (current-directory) "target/debug/librusty411.so")))
(define rust-print (get-ffi-obj "display_string" rust-lib (_fun _bytes _uint -> _void)))
;; Wrap ffi call
(define (call-rust-print str)
(let* ([str_ptr (string->bytes/utf-8 str)]
[len (bytes-length str_ptr)])
(rust-print str_ptr len)))
(module+ main
(call-rust-print "Hello, from Racket!"))
# Cargo.toml preamble ...
[lib]
crate-type=["cdylib"]
[dependencies]
libc = "0.2.169"
# ...
use libc::c_uint;
use std::slice;
use std::str;
#[no_mangle]
pub extern "C" fn display_string(data: *mut u8, len: c_uint) {
let len = len as usize;
let sl = unsafe { slice::from_raw_parts(data, len) };
let st = str::from_utf8(sl).unwrap();
println!("{:?}", st);
}
Sadly Racket’s FFI doesn’t make it easy to play with quazi-quoted lists for lots of obvious reasons…