Last active
March 6, 2020 22:46
-
-
Save borkdude/8446e14c713cc06e1d3f231c0d032017 to your computer and use it in GitHub Desktop.
Call a Rust function from C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
rustc --crate-type=dylib hello.rs | |
gcc hello.c -o hello | |
./hello # Just called a Rust function from C! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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