61 releases

Uses new Rust 2024

new 0.15.0-alpha.4 Apr 10, 2025
0.14.25 Jun 20, 2024
0.14.24 Mar 16, 2024
0.14.18 May 21, 2023
0.5.1 Jul 30, 2021

#324 in FFI

Download history 212/week @ 2024-12-20 450/week @ 2024-12-27 444/week @ 2025-01-03 961/week @ 2025-01-10 280/week @ 2025-01-17 218/week @ 2025-01-24 655/week @ 2025-01-31 285/week @ 2025-02-07 7/week @ 2025-02-14 8/week @ 2025-02-21 49/week @ 2025-02-28 92/week @ 2025-03-07 203/week @ 2025-03-14 184/week @ 2025-03-21 67/week @ 2025-03-28 271/week @ 2025-04-04

742 downloads per month
Used in 2 crates

MIT license

210KB
4K SLoC

Generates C bindings for Interoptopus.

Usage

Assuming you have written a crate containing your FFI logic called example_library_ffi and want to generate C bindings, follow the instructions below.

Inside Your Library

Add Interoptopus attributes to the library you have written, and define an inventory function listing all symbols you wish to export. An overview of all supported constructs can be found in the reference project.

use interoptopus::{ffi_function, ffi_type, function};
use interoptopus::inventory::{Inventory, InventoryBuilder};

#[ffi_type]
pub struct Vec2 {
    pub x: f32,
    pub y: f32,
}

#[ffi_function]
pub fn my_function(input: Vec2) -> Vec2 {
    input
}

pub fn my_inventory() -> Inventory {
    InventoryBuilder::new()
        .register(function!(my_function))
        .validate()
        .build()
}

Add these to your Cargo.toml so the attributes and the binding generator can be found (replace ... with the latest version):

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
interoptopus = "..."
interoptopus_backend_c = "..."

Create a unit test in tests/bindings.rs which will generate your bindings when run with cargo test. In real projects you might want to add this code to another crate instead:

use interoptopus::backend::NamespaceMappings;
use interoptopus::Error;

#[test]
fn bindings_c() -> Result<(), Error> {
    use interoptopus_backend_c::{Config, Interop};

    Interop::new(
        Config {
            ifndef: "example_library".to_string(),
            ..Config::default()
        },
        example_library_ffi::my_inventory(),
    ).write_file("bindings/c/example_complex.h")?;

    Ok(())
}

Now run cargo test.

If anything is unclear you can find a working sample on Github.

Generated Output

The output below is what this backend might generate. Have a look at the Config struct if you want to customize something. If you really don't like how something is generated it is easy to create your own.

// Automatically generated by Interoptopus.

#ifndef example_library
#define example_library

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>
#include <stdbool.h>

typedef struct vec2
    {
    float x
    float y;
    } vec2;


vec2 my_function(vec2 input);

#ifdef __cplusplus
}
#endif

#endif /* example_library */

Dependencies

~0.7–1.2MB
~25K SLoC