Module safer_ffi::headers

source ·
Available on crate feature headers only.
Expand description

C headers generation.

This module is only enabled when the "headers" feature of ::safer_ffi is enabled, which is expected to be done through a cargo feature within the (downstream) crate defining the #[ffi_export]ed functions.

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

[features]
generate-headers = ["safer-ffi/headers"]

Then, to generate the bindings, just define a #[safer_ffi::cfg_headers]-gated #[test] function, which can then call the builder to do the work:

use ::std::{io, fs};
use ::safer_ffi::prelude::*;

/// Concatenate two strings.
///
/// The returned value must be freed with `rust_free`
#[ffi_export]
fn rust_concat (fst: char_p::Ref<'_>, snd: char_p::Ref<'_>)
  -> char_p::Box
{
    let s: String = format!("{}{}\0", fst, snd);
    s   .try_into() // Try to convert to a boxed `char *` pointer
        .unwrap()   // Only fails if there is an inner nul byte.
}

/// Frees a pointer obtained by calling `rust_concat`.
#[ffi_export]
fn rust_free (it: char_p::Box)
{
    drop(it);
}

#[::safer_ffi::cfg_headers]
#[test]
fn generate_c_header ()
  -> io::Result<()>
{
    ::safer_ffi::headers::builder()
        .with_guard("__ASGARD__")
        .to_file("filename.h")?
        .generate()
}

so that

cargo test --features generate-headers -- \
    --exact generate_c_header \
    --nocapture

generates a "filename.h" file (⚠️ overwriting it if it exists ⚠️) with the following contents:

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

#ifndef __ASGARD__
#define __ASGARD__


/** \brief
 *  Concatenate two strings.
 * 
 *  The returned value must be freed with `rust_free_string`
 */
char * rust_concat (
    char const * fst,
    char const * snd);

/** \brief
 *  Frees a pointer obtained by calling `rust_concat`.
 */
void rust_free_string (
    char * it);


#endif /* __ASGARD__ */

Modules

Structs

Enums

Traits

  • Helper for the generation of C headers.

Functions