Rust ffi
Created By: chatGPT
extern "C" {
fn c_function(arg: i32) -> i32;
}
To get started, you need to ensure that you have a functioning Rust setup on your machine. You can create a new Rust project by running:
bash cargo new rust_ffi_example cd rust_ffi_example
Next, modify your Cargo.toml
file to include the following settings that enable linking with C code:
toml [lib] dynamically_linked = true
Now let's define a simple C function in a separate file. Create a file named c_code.c
in your project root and add the following code:
c
include <stdio.h>
int c_function(int arg) { printf("C received: %d\n", arg); return arg * 2; }
This C function takes an integer, prints it, and returns double its value.
To compile and link the C code, you'll need to include this file in your Rust build. You can do this by telling Rust to link against the C object file. Update your build.rs
file (create it in the project root if it doesn’t exist) with:
rust fn main() { println!("cargo:rustc-link-search=."); println!("cargo:rustc-link-lib=static=my_c_code"); }
Ensure your C code is compiled into an object file that Rust can link against.
Now, write the main Rust function in your src/main.rs
file to call this C function:
rust mod libc;
fn main() { unsafe { let result = c_function(5); println!("Result from C function: {}", result); } }
In this example, we call the c_function
from the main
function, passing it the integer 5
.
Finally, build your project using:
bash cargo build
And run it using:
bash cargo run
You should see output similar to:
C received: 5 Result from C function: 10
This demonstrates a simple FFI interaction between Rust and C, showcasing how to effectively communicate across language boundaries.