Skip to content
Luca Barbato edited this page Jun 25, 2019 · 3 revisions

TL;DR

Cargo-c let you produce all you need to make your crate used by C-ABI consumers, mimicking a normal C library.

Setup your crate

Cargo.toml

  • Make sure you have only a lib target, the first one will be used.
  • The .pc file will be produced using the version and description provided by the project.

lib.rs

You can put the C-API in a module and import it using the cargo_c cfg:

// lib.rs
#[cfg(cargo_c)] {
    // Opaque
    pub struct MyOpaqueStruct {
        inner: MyRustStruct,
        ...
    }

    pub unsafe extern "C" fn mycrate_mystruct_new() -> *mut MyOpaqueStruct { ... }

    // Not Opaque
    #[repr(C)]
    pub struct MyOtherStruct {
        pub field: u32,
        ...
    }
}

Under the hood cbindgen is being used, you may tweak its setting using a cbindgen.toml configuration.

Install

$ git clone https://github.com/lu-zero/cargo-c
$ cd cargo-c
$ cargo install --path .
$ cd your_crate
$ cargo cinstall --prefix=/usr

You will have:

├── include
│  └── your_crate
│     └── your_crate.h
└── lib
   ├── libyour_crate.0.1.2.dylib
   ├── libyour_crate.0.dylib
   ├── libyour_crate.a
   ├── libyour_crate.dylib
   └── pkg-config
      └── your_crate.pc
Clone this wiki locally