Add some more extern C code.

This commit is contained in:
Jesse Brault 2024-11-22 20:01:10 -06:00
parent 40b27e3b80
commit d9ed588c0e
3 changed files with 24 additions and 7 deletions

View File

@ -1,7 +1,5 @@
fn main() {
// Tell Cargo to rerun if the c file is changed
println!("cargo:rerun-if-changed=src/test.c");
cc::Build::new()
.file("src/test.c")
.compile("test");
cc::Build::new().file("src/test.c").compile("test");
}

View File

@ -13,18 +13,28 @@ impl Greeter {
Greeter { greeting }
}
fn greet(&self) {
pub fn greet(&self) {
println!("{}", self.greeting);
}
}
extern "C" {
fn print_num(num: i32);
fn print_a_string(s: *const u8, len: usize);
}
fn main() {
Greeter::new("Hello, Jesse!").greet();
// Calling some C
let original_s = "Hello from C-Rust land!";
unsafe {
print_a_string(original_s.as_ptr(), original_s.len());
}
// Testing out stack
let mut my_stack = Stack::new();
my_stack.push(Greeter::new("Hello"));
my_stack.push(Greeter::new("Beautiful"));
@ -49,5 +59,7 @@ fn main() {
// calling some C
let find_result = bst.find(3).unwrap_or(-1);
unsafe { print_num(find_result); }
unsafe {
print_num(find_result);
}
}

View File

@ -1,5 +1,12 @@
#include <stdio.h>
void print_num(int num) {
void print_num(const int num) {
printf("[from c]: num is %d\n", num);
}
void print_a_string(const char* s, const size_t length) {
for (int i = 0; i < length; i++) {
printf("%c", s[i]);
}
printf("\n");
}