::safer_ffi

CI

The User Guide

The recommended way to learn about ::safer_ffi is through the user guide:

πŸ“š Read the ::safer_ffi User guide hereπŸ“š

Prerequisites

Minimum Supported Rust Version: 1.43.0

Quickstart

Cargo.toml

Edit your Cargo.toml like so:

```toml [package] name = "crate_name" version = "0.1.0" edition = "2018"

[lib] crate-type = ["staticlib"]

[dependencies] safer-ffi = { version = "*", features = ["proc_macros"] }

[features] c-headers = ["safer-ffi/headers"] ```

src/lib.rs

```rust use ::safer_ffi::prelude::*;

/// A struct usable from both Rust and C

[derive_ReprC]

[repr(C)]

[derive(Debug, Clone, Copy)]

pub struct Point { x: f64, y: f64, }

/* Export a Rust function to the C world. */ /// Returns the middle point of [a, b].

[ffi_export]

fn mid_point ( a: &Point, b: &Point, ) -> Point { Point { x: (a.x + b.x) / 2., y: (a.y + b.y) / 2., } }

/// Pretty-prints a point using Rust's formatting logic.

[ffi_export]

fn print_point (point: &Point) { println!("{:?}", point); }

/// The following test function is necessary for the header generation.

[::saferffi::cfgheaders]

[test]

fn generateheaders () -> ::std::io::Result<()> { ::saferffi::headers::builder() .tofile("rustpoints.h")? .generate() }

```

Compilation & header generation

```bash

Compile the C library (in target/{debug,release}/libcrate_name.ext)

cargo build # --release

Generate the C header

cargo test --features c-headers -- generate_headers ```

Generated C header

``C /*! \file */ /******************************************* * * * File auto-generated by::safer_ffi`. * * * * Do not manually edit this file. * * * *************/

ifndef RUSTCRATENAME

define RUSTCRATENAME

ifdef __cplusplus

extern "C" {

endif

/** \brief * A struct usable from both Rust and C */ typedef struct {

double x;

double y;

} Point_t;

/** \brief * Returns the middle point of [a, b]. */ Pointt midpoint ( Pointt const * a, Pointt const * b);

/** \brief * Pretty-prints a point using Rust's formatting logic. */ void printpoint ( Pointt const * point);

ifdef __cplusplus

} /* extern "C" */

endif

endif /* RUSTCRATENAME */

```

Testing it

main.c

```C

include

include "rust_points.h"

int main (int argc, char const * const argv[]) { Pointt a = { .x = 84, .y = 45 }; Pointt b = { .x = 0, .y = 39 }; Pointt m = midpoint(&a, &b); printpoint(&m); return EXITSUCCESS; } ```

Compilation command

```bash cc main.c -o main -L target/debug -l crate_name

Now feel free to run the compiled binary

./main ```

which outputs:

text Point { x: 42.0, y: 42.0 }

πŸš€πŸš€