2

I need to create a (static) C library that binds to existing crate. Is there any way Cargo can create this C library for me?

I have a crate (e.g. html5ever), and I want Cargo to create a C library based on C-API for that crate.

Daniel Fath
  • 16,453
  • 7
  • 47
  • 82
  • You could take a look at [callbacks-from-c-code-to-rust-functions](http://doc.rust-lang.org/nightly/book/ffi.html#callbacks-from-c-code-to-rust-functions) – pd40 Mar 31 '15 at 23:29

3 Answers3

1

Is there any way Cargo can create this C library for me?

Cargo does not currently have this feature.

I have a crate (e.g. html5ever), and I want Cargo to create a C library based on C-API for that crate.

Is there a reason that it is in C? C can call into Rust code directly, you could just use html5ever as it exists.

Steve Klabnik
  • 14,521
  • 4
  • 58
  • 99
  • The problem at hand is, the thing guys at html5ever are trying to do is to have it's C-API created by Rust, so they can get rid of the Makefile whose only unique task is, creating C_API. Basically, move to Cargo, remove Makefile. – Daniel Fath Apr 01 '15 at 09:21
  • I'm surprised that Cargo doesn't allow some kind of CLI escape hatch. – Daniel Fath Apr 01 '15 at 09:22
0

A way to solve this problem is to create a special crate which stores your C API. For example if your library is called foo, then have inside your main directory another folder alongside src/tests called capi, which will store a special crate foo_capi for C API.

  foo
   |
   +--src
   | 
   +--test
   |
   +--capi
        | 
        +--include 
        |
        +--src 
        |
        Cargo.toml

include folder contains header files for C.

src contains the Rust files which are exported into C.

The Cargo manifest should be statically linked and have a dependency on the project foo. For example check out this Cargo.toml used in html5ever.

Daniel Fath
  • 16,453
  • 7
  • 47
  • 82
0

I think, cargo-c is excatly what you are looking for:

It produces and installs a correct pkg-config file, a static library and a dynamic library, and a C header to be used by any C (and C-compatible) software.

tpimh
  • 446
  • 2
  • 9
  • 23