Skip to content
This repository has been archived by the owner on Mar 10, 2022. It is now read-only.

giuseppe998e/rust-ffi-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Requirements

  1. rust (with cargo)
  2. gcc
  3. cbindgen

Compile the Rust library

$ cd testlib
$ cargo build --release
$ cbindgen --crate testlib --lang c --output ../testlib.h
$ cp target/release/libtestlib.{so,a} ..

Compile the C executable

Using the dynamic lib

$ gcc example.c -L. -ltestlib -o example.out

Using the static lib

$ gcc example.c libtestlib.a -ldl -pthread -o example.out

Execute

$ chmod +x example.out
$ LD_LIBRARY_PATH=. ./example.out

N.B. The environment variable LD_LIBRARY_PATH is only needed for the dynamic version of the library.


The Rust (dynamic) library could also be loaded at runtime using the dlfcn.h library.
This repository does not offer an example for this alternative.

Useful links

  1. FFI - Wikipedia
  2. FFI - Rustonomicon
  3. A little Rust with your C
  4. Exposing FFI from the Rust library
  5. Creating a shared and static library with gcc
  6. Minimizing Rust Binary Size
  7. CBindGen Quick Start

About

An example of how to use a dynamic or static library created with the Rust language in a program written in the C language (FFI)

Topics

Resources

License

Stars

Watchers

Forks