ruby_ffi_foreign_function_interface
Table of Contents
Ruby FFI (Foreign Function Interface)
Return to Ruby, Foreign Function Interface (FFI)
Overview
Ruby FFI (Foreign Function Interface) is a gem for Ruby that allows the execution of code written in other languages, such as C, directly from Ruby programs. It provides a way to dynamically load libraries, access their functions, and define custom data types. Ruby FFI eliminates the need for writing C extensions in Ruby and simplifies the process of interfacing with external libraries.
Key Features
- **Dynamic Library Loading:** Ruby FFI can load shared libraries at runtime, making it flexible and adaptable to different environments.
- **Function Binding:** It allows defining and binding to functions in the loaded libraries, specifying argument types and return values.
- **Custom Data Types:** Ruby FFI enables the creation of custom data types that mirror structures and unions in the C libraries.
- **Memory Management:** It handles memory allocation and deallocation for interacting with C data structures.
- **Callbacks:** FFI supports passing Ruby procs or blocks as callback functions to C libraries.
- **Platform Independence:** It is designed to work on multiple platforms, including Windows, macOS, and Linux.
Resources
- **GitHub Repository:** s://github.com/ffi/ffi(https://github.com/ffi/ffi)
- **RubyGems:** s://rubygems.org/gems/ffi(https://rubygems.org/gems/ffi)
- **Official Documentation:** [invalid URL removed]
Code Example
```ruby require 'ffi'
module MyLib
extend FFI::Library ffi_lib 'mylib.so'
# Define function signature attach_function :add, [:int, :int], :intend
- Call the C function
result = MyLib.add(5, 3) puts result # Output: 8 ```
In this example, `ffi_lib` loads the shared library `mylib.so`, `attach_function` defines the `add` function with its argument and return types, and then the `add` function is called directly from Ruby.
ruby_ffi_foreign_function_interface.txt · Last modified: 2025/02/01 06:31 by 127.0.0.1