# Complete Usage Example
This document demonstrates the complete workflow of using `bindings-generat` to create safe Rust bindings for a C library.
## Example: Simple Context Library
### Step 1: The C Library
We have a simple C library with this header (`simple_lib.h`):
```c
#ifndef SIMPLE_LIB_H
#define SIMPLE_LIB_H
// Status codes
typedef enum {
STATUS_OK = 0,
STATUS_ERROR_INVALID = 1,
STATUS_ERROR_NOT_FOUND = 2,
} SimpleStatus;
// Opaque context type
typedef struct simple_context_t simple_context_t;
// Create a new context
simple_context_t* simple_context_create(void);
// Set a value in the context
SimpleStatus simple_context_set_value(simple_context_t* ctx, int value);
// Get a value from the context
SimpleStatus simple_context_get_value(simple_context_t* ctx, int* out_value);
// Destroy the context
void simple_context_destroy(simple_context_t* ctx);
#endif
```
### Step 2: Run bindings-generat
```bash
bindings-generat \
--source ./examples/simple_lib \
--output ./simple-bindings \
--lib-name simple
```
### Step 3: Output
The tool performs these steps:
```
🔧 bindings-generat v0.1.0 - Automatic FFI Wrapper Generator
⠁ Phase 1: Preparing source...
✓ Source prepared: ./examples/simple_lib
✓ Found 1 header files
✓ Detected library: simple
⠁ Phase 2: Running bindgen...
✓ Generated FFI bindings (4 functions, 2 types)
⠁ Phase 3: Analyzing patterns...
✓ Found 1 handle types
✓ Detected 1 lifecycle pairs
⠁ Phase 4: Generating safe wrappers...
✓ Created RAII wrapper types
✓ Converted status codes to Error
⠁ Phase 5: Checking for LLM...
⚠ Ollama not detected, skipping LLM enhancement
⠁ Phase 6: Clarifying ambiguities...
ℹ No ambiguities detected
⠁ Phase 7: Writing output to ./simple-bindings...
✓ Created Cargo.toml
✓ Created src/lib.rs
✓ Created build.rs
⠁ Phase 8: Validating...
✓ Checking with cargo check... SUCCESS!
🎉 Done! Your safe Rust wrapper is ready.
Location: ./simple-bindings
Next steps:
cd ./simple-bindings
cargo doc --open
```
### Step 4: Generated Code
The generated `src/lib.rs` contains:
```rust
//! Safe Rust wrapper for simple
//!
//! This module was automatically generated by bindings-generat.
//! It provides safe, idiomatic Rust wrappers around the raw FFI bindings.
#![allow(dead_code)]
#![allow(non_camel_case_types)]
mod ffi {
// FFI bindings will be included here
// include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
}
/// Error type for this library
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
/// Null pointer returned
NullPointer,
/// STATUS_ERROR_INVALID
ErrorInvalid,
/// STATUS_ERROR_NOT_FOUND
ErrorNotFound,
/// Unknown error code
Unknown(i32),
}
impl From<ffi::SimpleStatus> for Error {
fn from(status: ffi::SimpleStatus) -> Self {
match status {
ffi::SimpleStatus::STATUS_ERROR_INVALID => Error::ErrorInvalid,
ffi::SimpleStatus::STATUS_ERROR_NOT_FOUND => Error::ErrorNotFound,
_ => Error::Unknown(status as i32),
}
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::NullPointer => write!(f, "Null pointer returned"),
Error::ErrorInvalid => write!(f, "error invalid"),
Error::ErrorNotFound => write!(f, "error not found"),
Error::Unknown(code) => write!(f, "Unknown error code: {}", code),
}
}
}
impl std::error::Error for Error {}
/// Safe wrapper for `simple_context_t`
pub struct SimpleContext {
handle: *mut simple_context_t,
}
impl SimpleContext {
/// Create a new instance
pub fn new() -> Result<Self, Error> {
unsafe {
let handle = ffi::simple_context_create();
if handle.is_null() {
Err(Error::NullPointer)
} else {
Ok(Self { handle })
}
}
}
/// Set a value in the context
pub fn set_value(&mut self, value: i32) -> Result<(), Error> {
unsafe {
let result = ffi::simple_context_set_value(self.handle, value);
if result == 0 {
Ok(())
} else {
Err(Error::from(result))
}
}
}
/// Get a value from the context
pub fn get_value(&mut self, out_value: *mut i32) -> Result<(), Error> {
unsafe {
let result = ffi::simple_context_get_value(self.handle, out_value);
if result == 0 {
Ok(())
} else {
Err(Error::from(result))
}
}
}
}
impl Drop for SimpleContext {
fn drop(&mut self) {
unsafe {
if !self.handle.is_null() {
ffi::simple_context_destroy(self.handle);
}
}
}
}
// Note: Implement Send/Sync manually if thread-safe
// unsafe impl Send for SimpleContext {}
// unsafe impl Sync for SimpleContext {}
```
### Step 5: Use the Generated Bindings
```rust
use simple_bindings::{SimpleContext, Error};
fn main() -> Result<(), Error> {
// Context is automatically created
let mut ctx = SimpleContext::new()?;
// Set a value - returns Result
ctx.set_value(42)?;
// Get the value
let mut value = 0;
ctx.get_value(&mut value)?;
println!("Value: {}", value);
// Context is automatically destroyed when it goes out of scope
Ok(())
}
```
## Key Benefits
### Before (Raw FFI)
```rust
unsafe {
let ctx = simple_context_create();
if ctx.is_null() {
panic!("Failed to create context");
}
let status = simple_context_set_value(ctx, 42);
if status != STATUS_OK {
simple_context_destroy(ctx);
panic!("Failed to set value");
}
// Must remember to destroy!
simple_context_destroy(ctx);
}
```
### After (Generated Bindings)
```rust
let mut ctx = SimpleContext::new()?;
ctx.set_value(42)?;
// Automatic cleanup!
```
## Advanced Usage
### With Configuration File
Create `bindings-generat.toml`:
```toml
[library]
source = "./examples/simple_lib"
output_path = "./simple-bindings"
lib_name = "simple"
[generation]
style = "ergonomic"
use_llm = false
[interactive]
enabled = false
```
Run:
```bash
bindings-generat
```
### With LLM Enhancement
If you have Ollama running:
```bash
bindings-generat \
--source ./examples/simple_lib \
--output ./simple-bindings \
--model deepseek-coder:6.7b
```
This will enhance documentation and suggest better naming.
### Interactive Mode
For complex libraries with ambiguous patterns:
```bash
bindings-generat \
--source ./complex-lib \
--output ./complex-bindings \
--interactive
```
The tool will ask questions about unclear patterns:
```
? This handle type has multiple possible destroy functions:
- complex_context_destroy
- complex_context_free
Which should be used? (Use arrow keys)
> complex_context_destroy
complex_context_free
```
## Troubleshooting
### Missing Headers
If headers aren't auto-detected:
```bash
bindings-generat \
--source ./lib \
--output ./bindings \
--headers "include/*.h"
```
### Library Name Issues
If the library name isn't detected correctly:
```bash
bindings-generat \
--source ./lib \
--output ./bindings \
--lib-name mylib
```
### Validation Failures
If the generated code doesn't compile:
1. Check the validation errors in the output
2. Use `--verbose` for detailed logs
3. Manually adjust the generated `src/lib.rs`
4. Consider filing an issue with your C library structure
## Best Practices
1. **Start Simple**: Begin with `--no-llm` and `--non-interactive`
2. **Review Output**: Always review the generated code
3. **Add Tests**: Write tests for your wrapper
4. **Document Assumptions**: Add comments about thread-safety
5. **Version Control**: Track your configuration file
## Real-World Example: libcurl
```bash
# Download libcurl source
wget https://curl.se/download/curl-8.4.0.tar.gz
# Generate bindings
bindings-generat \
--source curl-8.4.0.tar.gz \
--output curl-sys \
--lib-name curl
```
Result: Safe Rust bindings for libcurl with automatic cleanup of CURL handles!
---
For more examples, see the `examples/` directory in the repository.