From f0958ac2916c8ac8c71508a5ea14788532ec21bd Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Sun, 27 Dec 2020 15:09:31 +0800 Subject: [PATCH] feat: add ffi c --- __ffi/c2/Makefile | 16 ++++++++++++++++ __ffi/c2/README.md | 5 +++++ __ffi/c2/cfunctions.c | 15 +++++++++++++++ __ffi/c2/cfunctions.h | 2 ++ __ffi/c2/something.rs | 19 +++++++++++++++++++ 5 files changed, 57 insertions(+) create mode 100644 __ffi/c2/Makefile create mode 100644 __ffi/c2/README.md create mode 100644 __ffi/c2/cfunctions.c create mode 100644 __ffi/c2/cfunctions.h create mode 100644 __ffi/c2/something.rs diff --git a/__ffi/c2/Makefile b/__ffi/c2/Makefile new file mode 100644 index 0000000..9bd7011 --- /dev/null +++ b/__ffi/c2/Makefile @@ -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 + diff --git a/__ffi/c2/README.md b/__ffi/c2/README.md new file mode 100644 index 0000000..81f939b --- /dev/null +++ b/__ffi/c2/README.md @@ -0,0 +1,5 @@ + +url +https://github.com/danbev/learning-rust/tree/master/ffi + + diff --git a/__ffi/c2/cfunctions.c b/__ffi/c2/cfunctions.c new file mode 100644 index 0000000..f13d4c1 --- /dev/null +++ b/__ffi/c2/cfunctions.c @@ -0,0 +1,15 @@ +#include "cfunctions.h" +#include "stdio.h" +#include + +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); +} + diff --git a/__ffi/c2/cfunctions.h b/__ffi/c2/cfunctions.h new file mode 100644 index 0000000..e99409e --- /dev/null +++ b/__ffi/c2/cfunctions.h @@ -0,0 +1,2 @@ +void doit(int x); +void print_string(char* s); diff --git a/__ffi/c2/something.rs b/__ffi/c2/something.rs new file mode 100644 index 0000000..302a858 --- /dev/null +++ b/__ffi/c2/something.rs @@ -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()); + } +}