Draft
Conversation
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Author
|
Found this: https://bhh32.com/posts/tutorials/rust_ffi |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
[language/lang-code](example[python/fr]for Python in French or[java]for multiple Java translations)