54 releases

0.14.15 Nov 16, 2022
0.14.9 Jul 30, 2022
0.14.0 Feb 15, 2022
0.13.8 Nov 8, 2021
0.5.1 Jul 30, 2021

#2 in #headers

Download history 6/week @ 2022-10-09 6/week @ 2022-10-16 16/week @ 2022-10-23 23/week @ 2022-10-30 7/week @ 2022-11-06 30/week @ 2022-11-13 25/week @ 2022-11-20 37/week @ 2022-11-27 14/week @ 2022-12-04 10/week @ 2022-12-11 5/week @ 2022-12-18 12/week @ 2022-12-25 11/week @ 2023-01-01 13/week @ 2023-01-08 12/week @ 2023-01-15 17/week @ 2023-01-22

54 downloads per month
Used in interoptopus_backend_cpython_cffi

MIT license

175KB
3K 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, Inventory, InventoryBuilder, function};

#[ffi_type]
#[repr(C)]
pub struct Vec2 {
    pub x: f32,
    pub y: f32,
}

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

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

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::util::NamespaceMappings;
use interoptopus::{Error, Interop};

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

    Generator::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