Convert Figma logo to code with AI

rust-lang logorust-bindgen

Automatically generates Rust FFI bindings to C (and some C++) libraries.

4,361
687
4,361
425

Top Related Projects

5,795

Safe interop between Rust and C++

A project for generating C bindings from Rust code

Automatically generates Rust FFI bindings to C (and some C++) libraries.

Quick Overview

rust-lang/rust-bindgen is an automatic Rust binding generator for C and C++ libraries. It generates Rust FFI bindings to C and C++ libraries, allowing Rust programs to seamlessly interact with existing C/C++ code. This tool simplifies the process of integrating Rust with legacy codebases and external libraries.

Pros

  • Automates the creation of Rust bindings, saving time and reducing manual errors
  • Supports a wide range of C and C++ features, including complex types and templates
  • Highly configurable, allowing fine-tuning of generated bindings
  • Actively maintained and part of the official Rust project ecosystem

Cons

  • May generate suboptimal or overly verbose bindings for complex C++ code
  • Requires careful configuration for best results, which can be challenging for beginners
  • Some advanced C++ features may not be fully supported or may require manual intervention
  • Generated bindings may need additional manual tweaking for optimal Rust idiomatic usage

Code Examples

  1. Basic usage with a C header file:
use std::path::PathBuf;

fn main() {
    let bindings = bindgen::Builder::default()
        .header("wrapper.h")
        .generate()
        .expect("Unable to generate bindings");

    let out_path = PathBuf::from("bindings.rs");
    bindings
        .write_to_file(out_path)
        .expect("Couldn't write bindings!");
}
  1. Configuring bindgen for a specific library:
let bindings = bindgen::Builder::default()
    .header("libfoo.h")
    .allowlist_type("Foo")
    .allowlist_function("foo_.*")
    .generate()
    .expect("Unable to generate bindings");
  1. Generating bindings with custom derives:
let bindings = bindgen::Builder::default()
    .header("my_library.h")
    .derive_debug(true)
    .derive_default(true)
    .generate()
    .expect("Unable to generate bindings");

Getting Started

  1. Add bindgen to your Cargo.toml:

    [build-dependencies]
    bindgen = "0.64.0"
    
  2. Create a build.rs file in your project root:

    use std::env;
    use std::path::PathBuf;
    
    fn main() {
        println!("cargo:rerun-if-changed=wrapper.h");
    
        let bindings = bindgen::Builder::default()
            .header("wrapper.h")
            .generate()
            .expect("Unable to generate bindings");
    
        let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
        bindings
            .write_to_file(out_path.join("bindings.rs"))
            .expect("Couldn't write bindings!");
    }
    
  3. Include the generated bindings in your Rust code:

    #![allow(non_upper_case_globals)]
    #![allow(non_camel_case_types)]
    #![allow(non_snake_case)]
    
    include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
    

Competitor Comparisons

5,795

Safe interop between Rust and C++

Pros of cxx

  • Provides a more idiomatic and type-safe interface between Rust and C++
  • Offers bidirectional FFI, allowing seamless integration of Rust and C++ code
  • Generates both Rust and C++ code, ensuring compatibility and reducing manual work

Cons of cxx

  • Limited to C++17 and newer, potentially excluding older codebases
  • Has a steeper learning curve due to its unique syntax and concepts
  • May require more setup and configuration compared to rust-bindgen

Code Comparison

rust-bindgen:

#[repr(C)]
pub struct MyStruct {
    pub field: i32,
}

extern "C" {
    pub fn my_function(arg: *mut MyStruct);
}

cxx:

#[cxx::bridge]
mod ffi {
    struct MyStruct {
        field: i32,
    }

    unsafe extern "C++" {
        fn my_function(arg: &mut MyStruct);
    }
}

The cxx example demonstrates a more Rust-like syntax and safer interface, while rust-bindgen provides a lower-level C-style binding. cxx's approach often results in more idiomatic and easier-to-use Rust code when interacting with C++ libraries.

A project for generating C bindings from Rust code

Pros of cbindgen

  • Generates C/C++ bindings from Rust code, allowing easier integration of Rust libraries into C/C++ projects
  • Supports generating bindings for multiple C/C++ standards (C, C++11, C++14)
  • Provides fine-grained control over generated bindings through configuration files

Cons of cbindgen

  • Limited to generating C/C++ bindings from Rust, while rust-bindgen supports multiple input languages
  • May require more manual configuration and annotation of Rust code for optimal results
  • Less extensive documentation compared to rust-bindgen

Code Comparison

rust-bindgen (generating Rust bindings from C):

bindgen::Builder::default()
    .header("wrapper.h")
    .generate()
    .expect("Unable to generate bindings")
    .write_to_file(out_path.join("bindings.rs"))
    .expect("Couldn't write bindings!");

cbindgen (generating C bindings from Rust):

cbindgen::Builder::new()
    .with_crate(crate_dir)
    .generate()
    .expect("Unable to generate bindings")
    .write_to_file("bindings.h");

Both tools serve different purposes but share similar usage patterns. rust-bindgen focuses on generating Rust bindings from C/C++, while cbindgen generates C/C++ bindings from Rust. The choice between them depends on the specific project requirements and the direction of language integration needed.

Automatically generates Rust FFI bindings to C (and some C++) libraries.

Pros of rust-bindgen

  • Actively maintained and regularly updated
  • Extensive documentation and examples
  • Supports a wide range of C/C++ constructs

Cons of rust-bindgen

  • Can be complex to set up for advanced use cases
  • May generate verbose or suboptimal bindings in some cases
  • Limited support for certain C++ features

Code Comparison

rust-bindgen:

bindgen::Builder::default()
    .header("wrapper.h")
    .parse_callbacks(Box::new(bindgen::CargoCallbacks))
    .generate()
    .expect("Unable to generate bindings")
    .write_to_file(out_path.join("bindings.rs"))
    .expect("Couldn't write bindings!");

rust-bindgen:

bindgen::Builder::default()
    .header("wrapper.h")
    .parse_callbacks(Box::new(bindgen::CargoCallbacks))
    .generate()
    .expect("Unable to generate bindings")
    .write_to_file(out_path.join("bindings.rs"))
    .expect("Couldn't write bindings!");

Note: The code comparison shows identical usage for both repositories, as they are the same project. The comparison was requested between rust-lang/rust-bindgen and itself, so there are no differences to highlight in the code examples.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

crates.io docs.rs

bindgen

bindgen automatically generates Rust FFI bindings to C (and some C++) libraries.

For example, given the C header doggo.h:

typedef struct Doggo {
    int many;
    char wow;
} Doggo;

void eleven_out_of_ten_majestic_af(Doggo* pupper);

bindgen produces Rust FFI code allowing you to call into the doggo library's functions and use its types:

/* automatically generated by rust-bindgen 0.99.9 */

#[repr(C)]
pub struct Doggo {
    pub many: ::std::os::raw::c_int,
    pub wow: ::std::os::raw::c_char,
}

extern "C" {
    pub fn eleven_out_of_ten_majestic_af(pupper: *mut Doggo);
}

Users Guide

📚 Read the bindgen users guide here! 📚

MSRV

The bindgen minimum supported Rust version is 1.70.0.

The bindgen-cli minimum supported Rust version is 1.70.0.

No MSRV bump policy has been established yet, so MSRV may increase in any release.

The MSRV is the minimum Rust version that can be used to compile each crate. However, bindgen and bindgen-cli can generate bindings that are compatible with Rust versions below the current MSRV.

Most of the time, the bindgen-cli crate will have a more recent MSRV than bindgen as crates such as clap require it.

API Reference

API reference documentation is on docs.rs

Environment Variables

In addition to the library API and executable command-line API, bindgen can be controlled through environment variables.

End-users should set these environment variables to modify bindgen's behavior without modifying the source code of direct consumers of bindgen.

  • BINDGEN_EXTRA_CLANG_ARGS: extra arguments to pass to clang
    • Arguments are whitespace-separated
    • Use shell-style quoting to pass through whitespace
    • Examples:
      • Specify alternate sysroot: --sysroot=/path/to/sysroot
      • Add include search path with spaces: -I"/path/with spaces"
  • BINDGEN_EXTRA_CLANG_ARGS_<TARGET>: similar to BINDGEN_EXTRA_CLANG_ARGS, but used to set per-target arguments to pass to clang. Useful to set system include directories in a target-specific way in cross-compilation environments with multiple targets. Has precedence over BINDGEN_EXTRA_CLANG_ARGS.

Additionally, bindgen uses libclang to parse C and C++ header files. To modify how bindgen searches for libclang, see the clang-sys documentation. For more details on how bindgen uses libclang, see the bindgen users guide.

Releases

We don't follow a specific release calendar, but if you need a release please file an issue requesting that (ping @emilio for increased effectiveness).

Contributing

See CONTRIBUTING.md for hacking on bindgen!