]> piware.de Git - learn-rust.git/commitdiff
Call Rust function from C: Skeleton
authorMartin Pitt <martin@piware.de>
Fri, 27 Aug 2021 09:08:54 +0000 (11:08 +0200)
committerMartin Pitt <martin@piware.de>
Fri, 27 Aug 2021 09:49:13 +0000 (11:49 +0200)
.gitignore
call-rust-from-c/Cargo.toml [new file with mode: 0644]
call-rust-from-c/Makefile [new file with mode: 0644]
call-rust-from-c/src/lib.rs [new file with mode: 0644]
call-rust-from-c/src/main.c [new file with mode: 0644]

index 7ecae2e002a7ed8d2847b55e7db31df18052dfdc..125ba96f9392876a696a1671d9c54c45a8958364 100644 (file)
@@ -6,3 +6,6 @@ target
 libmount.rs
 c-langinfo
 c-mounts
 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 (file)
index 0000000..2868470
--- /dev/null
@@ -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 (file)
index 0000000..66a951a
--- /dev/null
@@ -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 (file)
index 0000000..f5e4384
--- /dev/null
@@ -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 (file)
index 0000000..b514433
--- /dev/null
@@ -0,0 +1,8 @@
+#include <stdio.h>
+#include "rustlib.h"
+
+int main()
+{
+    printf("The answer: %i\n", answer());
+    return 0;
+}