6 releases

Uses new Rust 2021

0.1.5 Mar 21, 2022
0.1.4 Mar 20, 2022

#77 in FFI

Download history 71/week @ 2022-03-12 64/week @ 2022-03-19 7/week @ 2022-03-26 8/week @ 2022-04-02 6/week @ 2022-04-09 6/week @ 2022-04-23 12/week @ 2022-04-30 42/week @ 2022-05-07 103/week @ 2022-05-14 19/week @ 2022-05-21 30/week @ 2022-05-28 43/week @ 2022-06-04 2/week @ 2022-06-18

75 downloads per month

MIT license

9KB
106 lines

c_import

This is a small proc macro crate providing a c_import macro (also a cpp_import macro), which can be used to import C headers into your program. It leverages bindgen, so bindgen needs to be installed in your system.

Usage

In your Cargo.toml:

# Cargo.toml

[depenedencies]
c_import = "0.1"

In your Rust source file:

// src/main.rs
use c_import::c_import;

c_import!(<cairo/cairo.h>);

fn main() {
    let version = unsafe { cairo_version() };
    println!("{}", version);
}

In your Rust build script:

// build.rs
fn main() {
    println!("cargo:rustc-link-lib=cairo");
}

Using non-system headers is also possible via enclosing the header path with quotation marks:

// src/main.rs
use c_import::c_import;
c_import!("src/my_header.h");

fn main() {
    let version = unsafe { cairo_version() };
    println!("{}", version);
}

Extra clang arguments

You can pass extra clang arguments as extra arguments to the macro:

// src/main.rs
use c_import::c_import;
c_import!("src/my_header.h", "-DMY_DEFINE", "-I/somepath/include");

fn main() {
    let version = unsafe { cairo_version() };
    println!("{}", version);
}

Usage with C++ headers (limited)

// src/main.rs
use c_import::cpp_import;

cpp_import!(<FL/Fl.H>);

fn main() {
    let version = unsafe { Fl::api_version() }; // static method of class Fl
    println!("{}", version);
}
// build.rs
fn main() {
    println!("cargo:rustc-link-lib=fltk");
}

Another example showing how to deal with C++ namespaces:

// src/my_header.hpp
#pragma once

namespace my_namespace {
class MyStruct {
    int version_;
  public:
    MyStruct(int version);
    int version() const;
};
}
// src/main.rs
use c_import::cpp_import;

cpp_import!("src/my_header.hpp");

fn main() {
    let h = unsafe { my_namespace_MyStruct::new(2) };
    println!("{}", unsafe { h.version() });
}

Limitations

  • Mostly bindgen limitations with C++ headers.

No runtime deps