Skip to content

Instantly share code, notes, and snippets.

@wware
Last active December 3, 2024 16:49
Show Gist options
  • Save wware/2b93fb5f20d20903e8cab409a5e0c939 to your computer and use it in GitHub Desktop.
Save wware/2b93fb5f20d20903e8cab409a5e0c939 to your computer and use it in GitHub Desktop.

How this stuff works

This is a Guile Scheme extension written in Rust instead of C. The longer-term goal is a Rust implementation of the Rete algorithm callable from Guile.

cargo build --release
sudo mkdir -p /usr/share/guile/site/3.0/
sudo rm -rf /usr/share/guile/site/3.0/rust*
sudo cp rust-example.scm /usr/share/guile/site/3.0
sudo cp target/release/deps/libguile_rust_example.so /usr/share/guile/site

Next, type guile tryit.scm to test it out.

[package]
name = "guile-rust-example"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
libc = "0.2"
// Put this file in a "src" subdirectory. Alas, github gists don't allow slashes in filenames, or directories.
use libc::c_char;
use std::ffi::CString;
#[no_mangle]
pub extern "C" fn rust_hello() -> *mut c_char {
let message = "Hello from Rust!";
let c_str = CString::new(message).unwrap();
c_str.into_raw()
}
#[no_mangle]
pub extern "C" fn rust_add(x: i32, y: i32) -> i32 {
x + y
}
// Free memory allocated by Rust
#[no_mangle]
pub extern "C" fn rust_free_string(ptr: *mut c_char) {
unsafe {
if !ptr.is_null() {
let _ = CString::from_raw(ptr);
}
}
}
(define-module (rust-example)
#:use-module (system foreign)
#:use-module (rnrs bytevectors)
#:export (rust-hello rust-add rust-free-string rust-string->scheme-string))
(define librust (dynamic-link "libguile_rust_example"))
(define rust-hello
(pointer->procedure '*
(dynamic-func "rust_hello" librust)
'()))
(define rust-add
(pointer->procedure int
(dynamic-func "rust_add" librust)
(list int int)))
(define rust-free-string
(pointer->procedure void
(dynamic-func "rust_free_string" librust)
'(*)))
(define (rust-string->scheme-string ptr)
(let ((str (pointer->string ptr)))
(rust-free-string ptr)
str))
(use-modules (rust-example))
(define msg (rust-hello))
(display (rust-string->scheme-string msg))
(newline)
(display (rust-add 5 3))
(newline)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment