Skip to content

Instantly share code, notes, and snippets.

@win-t
Created June 29, 2019 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save win-t/0001dc36dc357e83735c06577106693a to your computer and use it in GitHub Desktop.
Save win-t/0001dc36dc357e83735c06577106693a to your computer and use it in GitHub Desktop.
help: link against rust std
#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;
}
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
// 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)
}
@win-t
Copy link
Author

win-t commented Jun 29, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment