Skip to content

Conversation

@alycda
Copy link

@alycda alycda commented Nov 18, 2025

  • I solemnly swear that this is all original content of which I am the original author
  • Pull request title is prepended with [language/lang-code] (example [python/fr] for Python in French or [java] for multiple Java translations)
  • Pull request touches only one file (or a set of logically related files with similar changes made)
  • Content changes are aimed at intermediate to experienced programmers (this is a poor format for explaining fundamental programming concepts)
  • If you've changed any part of the YAML Frontmatter, make sure it is formatted according to CONTRIBUTING.md

alycda and others added 2 commits November 17, 2025 18:32
Added Section 6: FFI (Foreign Function Interface) covering:

**Calling C from Rust:**
- extern blocks for declaring C functions
- unsafe blocks for calling FFI functions
- Calling standard C library functions (abs, sqrt, puts)

**C-compatible types:**
- #[repr(C)] for structs, enums, and unions
- Type layout matching C expectations
- Opaque types for hidden C struct internals
- Type aliases for C types (c_int, c_char)

**Exposing Rust to C:**
- #[no_mangle] attribute to prevent name mangling
- pub extern "C" functions callable from C
- Null pointer validation
- Processing C data structures from Rust

**String handling:**
- CString for Rust → C string conversion
- CStr for C → Rust string conversion
- UTF-8 validation and error handling
- Safe conversion patterns

**Advanced patterns:**
- Function pointers and callbacks (extern "C" fn)
- Opaque handles with safe wrappers
- Passing arrays/slices to C functions
- Output parameters (mutable pointers)
- RAII pattern with Drop for cleanup

**Build integration:**
- Linking to C libraries with build.rs
- Using cc crate to compile C code
- #[link] attribute for system libraries
- bindgen for auto-generating bindings from headers

**Safety guidelines:**
- 7 key safety rules for FFI code
- Safe wrapper pattern around unsafe FFI
- Pointer validation (null checks)
- Lifetime and ownership considerations
- SafeHandle example with Drop implementation

**Resources:**
- Updated Further Reading with FFI-specific links
- Rustonomicon FFI chapter
- Rust FFI Omnibus
- bindgen, cbindgen, libc documentation

Tutorial expanded from 363 to 596 lines (+233 lines, 64% increase).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Based on deep analysis of dit-service-rust codebase, added 6
production-tested patterns from a real-world cross-platform library:

**Pattern 1: Multi-Mode Callback System**
- Enum supporting Rust closures, C function pointers, and JNI callbacks
- Context pointer pattern for stateful C callbacks
- unsafe impl Send/Sync with safety documentation
- Platform-specific variants with #[cfg(target_os)]

**Pattern 2: Safe Function Pointer Comparison**
- Using std::ptr::fn_addr_eq instead of direct == comparison
- Manual PartialEq implementation for platform-specific code
- Proper handling of function pointer uniqueness guarantees

**Pattern 3: Dependency Injection via Function Pointers**
- HttpRequest/HttpResponse/HttpError structs
- Platform HTTP client injection (NSURLSession, OkHttp)
- Global function pointer registration pattern
- Clear memory ownership contracts in struct docs

**Pattern 4: Null-Terminated Array Handling**
- Freeing C-allocated string arrays
- Iterating until NULL terminator
- Proper cleanup of nested malloc'd structures
- Using libc::free for C-allocated memory

**Pattern 5: JSON-Wrapped Error Returns**
- Never failing silently in FFI
- Structured error responses with codes and messages
- Success and error paths return same JSON format
- C callers parse consistent response structure

**Pattern 6: Singleton Management with OnceLock**
- Thread-safe one-time initialization
- AtomicBool for destruction tracking
- Preventing use-after-free with atomic flags
- Proper mutex + Box::from_raw pattern
- Non-recreatable after destruction

**Additional enhancements:**
- Real-world examples from production iOS/Android library
- Memory safety patterns for cross-platform code
- Platform-aware conditional compilation
- Clear ownership and lifetime documentation

Tutorial expanded from 596 to 793 lines (+197 lines, 33% increase).

These patterns are extracted from dit-service-rust, a production
library serving iOS, Android, and WebAssembly with comprehensive
FFI bridges and multi-platform support.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@alycda
Copy link
Author

alycda commented Nov 20, 2025

Found this: https://bhh32.com/posts/tutorials/rust_ffi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant