Skip to content

Instantly share code, notes, and snippets.

@jmpinit
Last active June 6, 2020 15:28
Show Gist options
  • Save jmpinit/5980297 to your computer and use it in GitHub Desktop.
Save jmpinit/5980297 to your computer and use it in GitHub Desktop.
How to use a shared library written in C from a program written in Rust. ( rust version 0.7. \ host: i686-unknown-linux-gnu ).
# so the lib can be found when the test is run
export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH
# alternatively put the .so generated after running make someplace where the system will find it
all:
gcc -Wall -fPIC -c *.c
gcc -shared -Wl,-soname,libsilly.so -o libsilly.so *.o
gcc -Wall -L./ test.c -lsilly -o test
rustc -L./ test-rust.rs
#include <stdio.h>
void silly_run(int num) {
printf("the silly number is %d\n", num);
}
use std::libc::c_int;
#[link_args = "-lsilly"]
extern {
fn silly_run(num: c_int) -> ();
}
fn main() {
unsafe { silly_run(5); }
println("Ran the unsafe code.");
}
void silly_run(int);
int main() {
silly_run(5);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment