From: Martin Pitt Date: Fri, 27 Aug 2021 09:08:54 +0000 (+0200) Subject: Call Rust function from C: Skeleton X-Git-Url: https://piware.de/gitweb/?a=commitdiff_plain;h=7ed2d982ac15df78e852fd5835d137881536a4ef;p=learn-rust.git Call Rust function from C: Skeleton --- diff --git a/.gitignore b/.gitignore index 7ecae2e..125ba96 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,6 @@ target libmount.rs c-langinfo c-mounts + +rustlib.h +main diff --git a/call-rust-from-c/Cargo.toml b/call-rust-from-c/Cargo.toml new file mode 100644 index 0000000..2868470 --- /dev/null +++ b/call-rust-from-c/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "call-rust-from-c" +version = "0.1.0" +edition = "2018" + +[lib] +crate-type = ['staticlib'] + +[dependencies] diff --git a/call-rust-from-c/Makefile b/call-rust-from-c/Makefile new file mode 100644 index 0000000..66a951a --- /dev/null +++ b/call-rust-from-c/Makefile @@ -0,0 +1,20 @@ +RLIB = target/debug/libcall_rust_from_c.a + +main: src/main.o $(RLIB) + $(CC) -Wall -o $@ $^ + +src/main.o: src/rustlib.h + +src/rustlib.h: src/lib.rs + cbindgen --lang c --output $@ + +$(RLIB): src/lib.rs + cargo build + +run: main + ./main + +check: + cargo test + +.PHONY: run test diff --git a/call-rust-from-c/src/lib.rs b/call-rust-from-c/src/lib.rs new file mode 100644 index 0000000..f5e4384 --- /dev/null +++ b/call-rust-from-c/src/lib.rs @@ -0,0 +1,26 @@ +use std::os::raw; + +/// Return The Answer. +/// +/// # Example +/// +/// ``` +/// let a = call_rust_from_c::answer(); +/// assert_eq!(a, 42); +/// ``` +#[no_mangle] +// C 'int'; it does not actually hurt to have more specific types such as int32_t, but it's good to know that plain ints work +pub extern "C" fn answer() -> raw::c_int { + return 42; +} + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_answer() { + assert_eq!(answer(), 42); + } +} diff --git a/call-rust-from-c/src/main.c b/call-rust-from-c/src/main.c new file mode 100644 index 0000000..b514433 --- /dev/null +++ b/call-rust-from-c/src/main.c @@ -0,0 +1,8 @@ +#include +#include "rustlib.h" + +int main() +{ + printf("The answer: %i\n", answer()); + return 0; +}