2017-04-27 17:41:01 -04:00
# `cbindgen`   [![Build Status]][travis] [![Latest Version]][crates.io]
[Build Status]: https://api.travis-ci.org/rlhunt/cbindgen.svg?branch=master
[travis]: https://travis-ci.org/rlhunt/cbindgen
[Latest Version]: https://img.shields.io/crates/v/cbindgen.svg
[crates.io]: https://crates.io/crates/cbindgen
2017-04-05 18:14:21 -04:00
2017-04-13 03:26:06 -04:00
This project can be used to generate C bindings for Rust code. It is currently being developed to support creating bindings for [WebRender ](https://github.com/servo/webrender/ ).
2017-04-11 18:26:14 -04:00
2017-04-17 21:39:40 -04:00
## Features
* Builds bindings for a crate, its mods, its dependent crates, and their mods
* Only the necessary types for exposed functions are given bindings
* Can specify directives for controlling some aspects of binding
* Generic structs can be exposed using `type IntFoo = Foo<i32>;`
2017-04-12 11:42:43 -04:00
## Use
2017-04-05 18:28:30 -04:00
2017-04-17 22:26:18 -04:00
### Command line
2017-04-13 03:26:06 -04:00
`cbindgen crate/ crate/bindings.h`
2017-04-12 11:42:43 -04:00
2017-04-17 22:26:18 -04:00
See `cbindgen --help` for more options.
### `build.rs`
`cbindgen` can also be used in build scripts. How this fits into compiling the native code depends on your project.
Here's an example build.rs script:
```rust
extern crate cbindgen;
2017-04-30 01:52:44 -04:00
use std::env;
2017-04-17 22:26:18 -04:00
use cbindgen::{Config, Library};
fn main() {
2017-04-30 01:52:44 -04:00
let root = env::var("CARGO_MANIFEST_DIR").unwrap();
let config = Config::from_root_or_default(&root);
2017-04-17 22:26:18 -04:00
2017-04-30 01:52:44 -04:00
Library::load(& root, & config)
2017-04-17 23:02:34 -04:00
.generate().unwrap()
2017-04-17 22:57:31 -04:00
.write_to_file("bindings.h");
2017-04-17 22:26:18 -04:00
}
2017-04-18 03:14:55 -04:00
2017-04-17 22:26:18 -04:00
```
2017-04-17 21:39:40 -04:00
## Examples
See `examples/` for some examples of rust source that can be handled.
2017-04-12 11:42:43 -04:00
## How it works
1. All the structs, enums, type aliases, and functions that are representable in C are gathered
2. A dependency graph is built using the extern "C" functions as roots
2017-04-17 21:39:40 -04:00
* This removes unneeded types from the bindings and sorts the structs that depend on each other
2017-04-12 11:42:43 -04:00
3. Some code generation is done to specialize generics that are specified as type aliases
3. The items are printed in dependency order in C syntax
## Future work
2017-04-13 03:26:06 -04:00
1. More customizable formatting and custom configs
2. Extensible system for specifying in source directives
3. Better support for types with fully specified names
4. Add a validation step
5. ...