README.md 1.99 KB
Newer Older
Ryan Hunt's avatar
Ryan Hunt committed
1
2
3
4
5
6
# `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
Kartikaya Gupta's avatar
Kartikaya Gupta committed
7

Ryan Hunt's avatar
Ryan Hunt committed
8
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/).
Kartikaya Gupta's avatar
Kartikaya Gupta committed
9

10
11
12
13
14
15
16
## 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>;`

Ryan Hunt's avatar
Ryan Hunt committed
17
## Use
Kartikaya Gupta's avatar
Kartikaya Gupta committed
18

19
20
### Command line

Ryan Hunt's avatar
Ryan Hunt committed
21
`cbindgen crate/ crate/bindings.h`
Ryan Hunt's avatar
Ryan Hunt committed
22

23
24
25
26
27
28
29
30
31
32
33
34
35
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;

use cbindgen::{Config, Library};

fn main() {
36
    let config = Config::from_file("cbindgen.toml");
37
38

    Library::load("../build-script", &config)
39
        .generate().unwrap()
Ryan Hunt's avatar
Ryan Hunt committed
40
        .write_to_file("bindings.h");
41
}
Ryan Hunt's avatar
Ryan Hunt committed
42

43
44
```

45
46
47
48
## Examples

See `examples/` for some examples of rust source that can be handled.

Ryan Hunt's avatar
Ryan Hunt committed
49
50
51
52
## 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
53
    * This removes unneeded types from the bindings and sorts the structs that depend on each other
Ryan Hunt's avatar
Ryan Hunt committed
54
55
56
57
58
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

Ryan Hunt's avatar
Ryan Hunt committed
59
60
61
62
63
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. ...