mohitmishra786/low-level-dev-skills / skills/rust/rust-ffi
rust-ffi
VerifiedRust FFI skill for C interoperability. Use when calling C libraries from Rust, generating Rust bindings with bindgen, exporting Rust functions to C with cbindgen, writing safe wrappers around unsafe FFI, or linking system and vendor libraries. Activates on queries about bindgen, cbindgen, extern "C", unsafe FFI, Rust C bindings, linking C from Rust, or sys crates.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 7.4 KB |
| references/bindgen-cbindgen.md | markdown | 4.9 KB |
references/bindgen-cbindgen.md
View on GitHub# bindgen and cbindgen Configuration Reference
## bindgen Options
### Builder configuration
```rust
bindgen::Builder::default()
.header("wrapper.h")
// Clang flags
.clang_arg("-I/usr/local/include")
.clang_arg("-DFEATURE=1")
.clang_arg("--target=aarch64-linux-gnu")
// Allowlist (generate only matching items)
.allowlist_function("mylib_.*")
.allowlist_type("MyLib.*|MyErr.*")
.allowlist_var("MYLIB_[A-Z_]+")
.allowlist_item("mylib_.*") // all: functions + types + vars
// Blocklist
.blocklist_function("mylib_internal_.*")
.blocklist_type("__.*")
// Derive traits on generated structs
.derive_debug(true)
.derive_copy(true)
.derive_default(true)
.derive_hash(true)
.derive_eq(true)
.derive_ord(true)
// Bit-field representation
.bitfield_enum("MyFlags")
// Newtype enum for type safety
.newtype_enum("MyError")
// Constified enum (generates constants, not enum)
.constified_enum_module("MyStatus")
// Opaque type (treat as opaque blob)
.opaque_type("FILE")
// Raw pointer → NonNull
.no_partialeq("MyStruct")
// Callback type as function pointer
.raw_line("#[allow(non_upper_case_globals, non_camel_case_types, non_snake_case)]")
// Dynamic loading instead of static link
// .dynamic_library_name("mylib")
// Rustified enum
.rustified_enum("MyEnum")
.generate()
```
### Command-line bindgen
```bash
# Install
cargo install bindgen-cli
# Generate
bindgen wrapper.h \
--allowlist-function 'mylib_.*' \
--allowlist-type 'MyLib.*' \
-- -I/usr/local/include \
> src/bindings.rs
```
### bindgen.toml (configuration file)
```toml
# bindgen.toml
allowlist_function = ["mylib_.*"]
allowlist_type = ["MyLib.*"]
derive_debug = true
derive_default = true
```
## cbindgen Options
### cbindgen.toml
```toml
# cbindgen.toml
language = "C" # or "C++"
[export]
include = ["MyLib", "MyError"] # Only export these
exclude = ["InternalState"]
[export.rename]
"MyLib" = "mylib_t" # Rename in generated header
[fn]
prefix = "MYLIB_API" # Add prefix to all function declarations
[defines]
# Generate #define guards
"feature_a" = "MYLIB_FEATURE_A"
[enum]
rename_variants = "ScreamingSnakeCase"
[struct]
derive_eq = true
derive_hash = true
[documentation]
# Include doc comments as C comments
style = "c" # "c" or "doxy"
```
### Language options
```rust
// build.rs
cbindgen::Builder::new()
.with_crate(&crate_dir)
// C output
.with_language(cbindgen::Language::C)
// C++ output with namespace
.with_language(cbindgen::Language::Cxx)
.with_namespace("mylib")
// Header guard
.with_include_guard("MYLIB_H")
// Include in header
.with_header("/* Generated by cbindgen */")
.with_after_include("#ifdef __cplusplus\nextern \"C\" {\n#endif")
.with_trailer("#ifdef __cplusplus\n}\n#endif")
.generate()
```
## cc Crate for Building C Code
```toml
[build-dependencies]
cc = "1.0"
```
```rust
// build.rs
fn main() {
cc::Build::new()
.files(["src/a.c", "src/b.c"])
.include("include/")
.define("FEATURE_X", "1")
.flag("-std=c11")
.flag_if_supported("-Wno-unused-parameter")
.pic(true) // Position-independent code
.static_flag(true) // Build static lib
.warnings(true)
.extra_warnings(true)
.compile("myhelper"); // Generates libmyhelper.a
// cc automatically emits:
// cargo:rustc-link-lib=static=myhelper
}
```
## pkg-config Integration
```toml
[build-dependencies]
pkg-config = "0.3"
```
```rust
// build.rs
fn main() {
match pkg_config::Config::new()
.atleast_version("2.0")
.statik(false)
.probe("mylib")
{
Ok(lib) => {
// pkg-config automatically emits link directives
// Expose include paths for bindgen
for path in &lib.include_paths {
println!("cargo:include={}", path.display());
}
}
Err(e) => {
eprintln!("pkg-config failed: {e}");
// Fallback to manual paths
println!("cargo:rustc-link-lib=mylib");
println!("cargo:rustc-link-search=/usr/local/lib");
}
}
}
```
## Common FFI Safety Patterns
### Null-checked constructor
```rust
pub fn new() -> Option<Self> {
let ptr = unsafe { ffi::create() };
if ptr.is_null() {
None
} else {
Some(Self { ptr })
}
}
```
### Lifetime-bounded reference
```rust
// Ensure Rust wrapper doesn't outlive C object
pub struct BorrowedHandle<'a> {
ptr: *mut ffi::handle_t,
_marker: std::marker::PhantomData<&'a ()>,
}
```
### Thread-safety annotations
```rust
// Mark safe to send between threads (verify C library is thread-safe first!)
unsafe impl Send for MyLib {}
// Mark safe to share between threads (verify C library uses internal locking)
unsafe impl Sync for MyLib {}
```
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |