Created
June 29, 2019 00:23
-
-
Save win-t/0001dc36dc357e83735c06577106693a to your computer and use it in GitHub Desktop.
help: link against rust std
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 <stdint.h> | |
extern void* create_vec(); | |
extern void free_vec(void*); | |
extern void push_vec(void*, int64_t); | |
extern void print_vec(void*); | |
int main() { | |
void* vec = create_vec(); | |
push_vec(vec, 3); | |
push_vec(vec, 7); | |
push_vec(vec, 7); | |
push_vec(vec, 9); | |
print_vec(vec); | |
free_vec(vec); | |
return 0; | |
} |
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
main: main.o vec.o | |
# how to link against rust std ? | |
# or can we compile rust std into staticlib ? | |
gcc -o main main.o vec.o | |
main.o: main.c | |
gcc -o main.o -c main.c | |
vec.o: vec.rs | |
rustc --emit obj --crate-type staticlib -o vec.o vec.rs | |
clean: | |
rm -f main *.o | |
.PHONY: clean |
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
// NOTE: ignoring panic and not using catch_unwind for simplicity | |
use std::mem::{drop, forget}; | |
#[no_mangle] | |
pub unsafe extern "C" fn create_vec() -> *mut Vec<i64> { | |
let vec = Box::new(vec![]); | |
Box::into_raw(vec) | |
} | |
#[no_mangle] | |
pub unsafe extern "C" fn free_vec(raw_vec: *mut Vec<i64>) { | |
let vec = Box::from_raw(raw_vec); | |
drop(vec) | |
} | |
#[no_mangle] | |
pub unsafe extern "C" fn push_vec(raw_vec: *mut Vec<i64>, data: i64) { | |
let mut vec = Box::from_raw(raw_vec); | |
vec.push(data); | |
forget(vec) | |
} | |
#[no_mangle] | |
pub unsafe extern "C" fn print_vec(raw_vec: *mut Vec<i64>) { | |
let vec = Box::from_raw(raw_vec); | |
for v in vec.as_ref() { | |
println!("{}", v); | |
} | |
forget(vec) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://users.rust-lang.org/t/how-to-link-against-rust-std/29741