Skip to content

CSS-Scripter/example_ffi-c-rust

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 

Repository files navigation

FFI | Foreign Function Interface

The aim is to create a function in C and call that function from Rust.

Background Info

To run C from Rust we first need to compile it to a library. There are two options for this:

  • Static library Includes all code, and does not require anything extra from the system, meaning larger file, but more independent. .a file for Linux/MacOs .lib file for Windows
  • Dynamic library Requires libraries from the OS, but results in smaller file size. .so for Linux/Unix/Android .dll for Windows .dylib for MacOS

Compiling C into .a

To compile our C code into a .a file, we'll need to run the makefile provided.

cd c_lib
make

This will create .o files, and a file called libclib.a. This file should always have the naming convention of lib{name}.a. In our case, our library is called clib.

Using .a file in rust

In the file rust_ffi/build.rs we can either tell Rust to look for the library file, or we can tell it how to compile the library file. The current code will compile it when running. Example code of how to point to the library file is as follows

fn main() {
	println!("cargo:rustc-link-search=native=../c_lib/");
	println!("cargo:rustc-link-lib=clib");
}

Running Rust

To actually run rust, we can simply run cargo run in the rust_ffi folder.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published