Skip to content

Instantly share code, notes, and snippets.

@borkdude
Last active March 6, 2020 22:46
Show Gist options
  • Save borkdude/8446e14c713cc06e1d3f231c0d032017 to your computer and use it in GitHub Desktop.
Save borkdude/8446e14c713cc06e1d3f231c0d032017 to your computer and use it in GitHub Desktop.
Call a Rust function from C
#!/usr/bin/env bash
rustc --crate-type=dylib hello.rs
gcc hello.c -o hello
./hello # Just called a Rust function from C!
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main() {
void *libhello;
libhello = dlopen("./libhello.dylib", RTLD_LAZY);
int (*hello)();
*(void **)(&hello) = dlsym(libhello, "call_from_c");
hello();
return EXIT_SUCCESS;
}
#[no_mangle]
pub extern "C" fn call_from_c() {
println!("Just called a Rust function from C!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment