feat: add ffi c
This commit is contained in:
16
__ffi/c2/Makefile
Normal file
16
__ffi/c2/Makefile
Normal file
@@ -0,0 +1,16 @@
|
||||
.PHONY: clean
|
||||
|
||||
libcfunctions.so: cfunctions.o
|
||||
${CC} --shared -o $@ $<
|
||||
|
||||
cfunctions.o: cfunctions.h cfunctions.c
|
||||
${CC} -fPIC -o $@ -c cfunctions.c -I.
|
||||
|
||||
something: something.rs libcfunctions.so
|
||||
rustc -L. -lcfunctions something.rs -C link-arg='-Wl,-rpath,${PWD}'
|
||||
@# The command below can be used if the library to link with is
|
||||
@# specified in something.rs.
|
||||
@#rustc -L. something.rs -C link-arg='-Wl,-rpath,${PWD}'
|
||||
clean:
|
||||
${RM} libcfunctions.so cfunctions.o something
|
||||
|
||||
5
__ffi/c2/README.md
Normal file
5
__ffi/c2/README.md
Normal file
@@ -0,0 +1,5 @@
|
||||
|
||||
url
|
||||
https://github.com/danbev/learning-rust/tree/master/ffi
|
||||
|
||||
|
||||
15
__ffi/c2/cfunctions.c
Normal file
15
__ffi/c2/cfunctions.c
Normal file
@@ -0,0 +1,15 @@
|
||||
#include "cfunctions.h"
|
||||
#include "stdio.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
void doit(int nr) {
|
||||
printf("Do something. nr: %d\n", nr);
|
||||
printf("Going to call exit\n");
|
||||
exit(1);
|
||||
printf("After calling exit\n");
|
||||
}
|
||||
|
||||
void print_string(char* s) {
|
||||
printf("print_string. s: %s\n", s);
|
||||
}
|
||||
|
||||
2
__ffi/c2/cfunctions.h
Normal file
2
__ffi/c2/cfunctions.h
Normal file
@@ -0,0 +1,2 @@
|
||||
void doit(int x);
|
||||
void print_string(char* s);
|
||||
19
__ffi/c2/something.rs
Normal file
19
__ffi/c2/something.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
use std::ffi::CString;
|
||||
use std::os::raw::c_char;
|
||||
|
||||
// The below can be left out if the library is specified to
|
||||
// rustc as an option.
|
||||
//#[link(name = "cfunctions", kind="dylib")]
|
||||
extern "C" {
|
||||
fn doit(nr: i32) -> ();
|
||||
fn print_string(s: *const c_char) -> ();
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("Example of calling a c library.");
|
||||
let s = CString::new("bajja").expect("CString::new failed");
|
||||
unsafe {
|
||||
doit(18);
|
||||
print_string(s.as_ptr());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user