SlideShare a Scribd company logo
1 of 23
Introduction
to
Ruby Native Extensions
and
Foreign Function Interface
https://github.com/suhovius/ruby_c_experiments
Oleksii Sukhovii
In order to compile C code make and gcc (or
clang for macOS) should be installed.
At systems with the APT package manager:
$ sudo apt install -y make gcc
Native Extension
● C code that’s included inside the Ruby gem
● Calls the external components API
● Converts parameters and return values between the external library format and Ruby
interpreter expectations
● Native Extension C code is directly executed by VM (MRI, YARV, etc)
Why do we write C extensions?
● Ruby’s C APIs are bridge between the Ruby and
C world
● High performing C code which is directly
connected to Ruby code (No need to waste the
time for data interchange between different
processes or services)
● Integratoin with C libraries (nokogiri, mysql2)
Why we do NOT write C extensions?
● 10x harder to write, maintain, and understand
● More issues to consider, such as memory
management and type safety
● Ruby API is huge and largely undocumented
● Might require delving through the Ruby source code
● Ruby source uses some fairly sophisticated C
Ruby Gem
with
Native C
Extensions
Compile the extension:
rake compile:math_demo
Use extension in the gems
console: bin/console
> MathDemo.c_pow(3, 2)
=> 9.0
extconf.rb
MakeMakefile
https://www.rubydoc.info/stdlib/mkmf/Ma
keMakefile - mkmf docs
https://silverhammermba.github.io/embe
rb/extend/ - docs
https://makefiletutorial.com/ - Makefiles
tutorial
https://github.com/dmke/ktoblzcheck/blo
b/master/ext/ktoblzcheck/extconf.rb -
original extconf.rb file
mkmf.rb is used by Ruby C extensions
to generate a Makefile which will
correctly compile and link the C
extension to Ruby and a third-party
library.
extconf.rb Examples
https://github.com/dmke/ktoblzcheck/blob/master/ext/ktoblzcheck/extconf.rb
https://github.com/nathanstitt/pdfium-ruby/blob/master/ext/pdfium_ext/extconf.rb
Nokogiri
https://github.com/sparklemotion/nokogiri/blob/main/ext/nokogiri/extconf.rb
Memcached
https://github.com/arthurnn/memcached/blob/master/ext/memcached/extconf.rb
https://github.com/kubo/ruby-flite/blob/master/ext/flite/extconf.rb
https://github.com/ohai/ruby-sdl2/blob/master/extconf.rb
Ruby C API
● #include <ruby.h> - header with Ruby C API Macros
● void Init_math_demo() - called when compiled extension
file is required: require ‘math_demo/math_demo’
● ID id_puts = rb_intern("puts") - type and method that
converts C string to ruby symbol :puts
● Type VALUE represents Ruby Object within C
● void rb_define_method(VALUE klass, const char *name,
VALUE (*func)(ANYARGS), int argc);
● NUM2DBL(rb_value), DBL2NUM(c_value) - few of many
Ruby to C and C to Ruby conversion macroses
Ruby Native C Useful
Links
https://blog.peterzhu.ca/ruby-c-ext/ - A Rubyist's Walk Along the C-side
http://silverhammermba.github.io/emberb/c/ - The Ruby C API
https://github.com/andremedeiros/ruby-c-cheat-sheet - Ruby C Cheat Sheet
https://github.com/ruby/ruby/blob/master/doc/extension.rdoc - Official documentation
https://github.com/miyucy/sophia-ruby/blob/master/ext/sophia.c - Good practical usage example
https://dev.to/vinistock/creating-ruby-native-extensions-kg1 - Creating Ruby native extensions
http://aaronbedra.com/extending-ruby/ - libxml example
http://clalance.blogspot.com/2011/01/writing-ruby-extensions-in-c-part-1.html - In-depth series on Ruby
extensions in C
https://ruby-doc.com/docs/ProgrammingRuby/html/ext_ruby.html - Extending Ruby
● https://github.com/seattlerb/rubyinline - gem
● Allows to write foreign code within ruby code
● Automatically determines if the code has
changed and builds it only when necessary
● Extensions are then automatically loaded into
the class/module that defines it
● Code is being compiled on the fly, so first run
might be slow, then it is cached for next call
● Not supporting alternative names for data
types at called function signature (Ignores
their definitions in the headers, maybe
requires some unknown magic to fix it)
Ruby Inline
Foreign Function Interface
(Ruby-FFI gem)
● Loading dynamically-linked native
libraries programmatically
● Binding functions within libraries
● Calling these functions from Ruby
code
● Works without changes on CRuby
(MRI), JRuby, Rubinius and
TruffleRuby
Requirements
C compiler (Xcode, gcc, clang)
libffi library and dev headers (libffi-
dev or libffi-devel packages)
https://github.com/ffi/ffi/wiki/why-use-ffi
Features
● Intuitive DSL
● Supports all C native types
● C structs (also nested), enums and global variables
● Callbacks from C to Ruby
● Automatic garbage collection of native memory
FFI Basic Usage
attach_function
● First argument* gives the name we want to use when calling the method, - so snake-case 🐍
instead of camel-case 🐫
● Second argument is the actual name of the function in the C library so FFI can find it
● Third argument is an array of types which informs FFI of the argument types we expect to be
passing in (in order)
● The last argument is the expected type of the return value
ffi_lib
● loads ‘libh3’ library
● accepts names of or paths
to libraries to load
FFI Useful Links
● https://github.com/ffi/ffi gem docs and wiki https://github.com/ffi/ffi/wiki
● https://www.rubydoc.info/github/ffi/ffi - ruby doc
● https://www.rubyguides.com/2019/05/ruby-ffi/ - Play Media Files with VLC and FFI
● https://stuart.com/blog/tech/ruby-bindings-extensions/ - FFI examle with Uber H3 library
https://github.com/StuartApp/h3_ruby - ruby gem that connects with H3 library via FFI
● https://github.com/hybridgroup/rubyserial/blob/master/lib/rubyserial/linux_constants.rb - usage
example with method attachment and C structs
● https://www.varvet.com/blog/advanced-topics-in-ruby-ffi/ - Advanced Topics
● https://spin.atomicobject.com/2013/02/15/ffi-foreign-function-interfaces/ - Foreign Function
Interfaces for Fun & Industry
Fiddle
● Added to Ruby's standard library in 1.9.x
● Fiddle is an extension to translate a foreign
function interface (FFI) with ruby.
● Wraps libffi, a popular C library which provides
a portable interface that allows code written in
one language to call code written in another
language
● Allows to inspect and alter the ruby
interpreter as it runs
Fiddle Usage
Fiddle::Importer - A DSL that provides the means to dynamically
load libraries and build modules around them including calling extern
functions within the C library that has been loaded. https://ruby-
doc.org/stdlib-2.5.3/libdoc/fiddle/rdoc/Fiddle/Importer.html
Fiddle Useful Links
● https://www.honeybadger.io/blog/use-any-c-library-from-ruby-via-fiddle-the-ruby-standard-
librarys-best-kept-secret/ - Use any C library from Ruby via Fiddle
● https://medium.com/@astantona/fiddling-with-rubys-fiddle-39f991dd0565 - Fiddling with
Ruby’s Fiddle
● https://stackoverflow.com/questions/50785133/ruby-fiddle-define-struct - Ruby Fiddle
Structs
● https://ruby-doc.org/stdlib-3.0.2/libdoc/fiddle/rdoc/Fiddle.html rDoc
● https://github.com/ruby/fiddle Gem
Performance Benchmarks
For Levenshtein distance algorithm
Approach Iterations Per Second Elapsed time Memory Allocations
Native C Extension
(Ruby C APi)
1544254.8 i/s 0.000009 40 allocated
Ruby Inline 1342312.5 i/s - 1.15x
(± 0.00) slower
0.000011 80 allocated - 2.00x
more
FFI 1291394.3 i/s - 1.20x
(± 0.00) slower
0.000013 40 (same as Native C)
Fiddle 269478.0 i/s - 5.73x (±
0.00) slower
0.000025 317 allocated - 7.92x
more
Ruby, RubyGems algorithm 111615.4 i/s - 13.84x
(± 0.00) slower
0.000126 528 allocated - 13.20x
more
Usability Comparison
Approach Pros Cons
Native C
Extension
(Ruby C APi)
Huge Performance as it is the most close
to Native C as Ruby can get to
Usage complexity, low level coding (memory
management, type safety), boilerplate code,
not fully documented
Ruby Inline Simplest usage for Native C.
Just copy-paste the C code into Ruby
and run it inline. No need to compile
code separately.
1.15x times slower and 2x times allocates more
memory than native C
Compilation at runtime
Not working with dynamically linked libraries
FFI Easy to use, automatic garbage
collection, customizable, good level of
control, good documentation.
1.2x times slower than native C
Not ruby stdlib gem as Fiddle
Fiddle Simplest FFI, almost verbatim mapping
of the C code to Ruby. Ruby stdlib gem.
4.5x times slower and 7.92x times allocates
more memory than FFI
Ruby Easy and comfortable for Rubyists. The
most programmer friendly solution
13.84x times slower and 13.20x more memory
usage as it can not compete with Native C
I need C code in Ruby
(For Performance or External C Library Integration)
Yes No
Super Fast!
Memory Efficient!
Do not care about complexity!
Fast and Easy
Native Ruby C API FFI
Which one
to choose?
Easier / No Dependencies
(Ruby Stdlib) / Slower
Fiddle
Few lines of C Code
Ruby Inline
Do you really need C for
so few lines of code?
Yes No
Faster and
Memory Efficient
Ruby
● https://www.learn-c.org/ Learn C
● https://www.tutorialspoint.com/cprogramming/index.htm C Tutorial
● https://github.com/oz123/awesome-c Some C Libraries to practice Ruby integration
● https://vtd-xml.sourceforge.io/ Good C Library to practice Ruby Integration,
Especially this https://vtd-xml.sourceforge.io/codeSample/cs4.html example
● https://riptutorial.com/ruby/example/17682/working-with-c-structs Working with C
Structs via Ruby Native C API
More of the Useful Links! :)
Questions
?

More Related Content

What's hot

Spacecrafts Made Simple: How Loft Orbital Delivers Unparalleled Speed-to-Spac...
Spacecrafts Made Simple: How Loft Orbital Delivers Unparalleled Speed-to-Spac...Spacecrafts Made Simple: How Loft Orbital Delivers Unparalleled Speed-to-Spac...
Spacecrafts Made Simple: How Loft Orbital Delivers Unparalleled Speed-to-Spac...
InfluxData
 
Synchronous Commands over Apache Kafka (Neil Buesing, Object Partners, Inc) K...
Synchronous Commands over Apache Kafka (Neil Buesing, Object Partners, Inc) K...Synchronous Commands over Apache Kafka (Neil Buesing, Object Partners, Inc) K...
Synchronous Commands over Apache Kafka (Neil Buesing, Object Partners, Inc) K...
confluent
 
Vyacheslav Zholudev – Flink, a Convenient Abstraction Layer for Yarn?
Vyacheslav Zholudev – Flink, a Convenient Abstraction Layer for Yarn?Vyacheslav Zholudev – Flink, a Convenient Abstraction Layer for Yarn?
Vyacheslav Zholudev – Flink, a Convenient Abstraction Layer for Yarn?
Flink Forward
 

What's hot (20)

Search engine based on Elasticsearch
Search engine based on ElasticsearchSearch engine based on Elasticsearch
Search engine based on Elasticsearch
 
Flink Forward San Francisco 2018: Xu Yang - "Alibaba’s common algorithm platf...
Flink Forward San Francisco 2018: Xu Yang - "Alibaba’s common algorithm platf...Flink Forward San Francisco 2018: Xu Yang - "Alibaba’s common algorithm platf...
Flink Forward San Francisco 2018: Xu Yang - "Alibaba’s common algorithm platf...
 
Building a fully Kafka-based product as a Data Scientist | Patrick Neff, BAADER
Building a fully Kafka-based product as a Data Scientist | Patrick Neff, BAADERBuilding a fully Kafka-based product as a Data Scientist | Patrick Neff, BAADER
Building a fully Kafka-based product as a Data Scientist | Patrick Neff, BAADER
 
Introduction to Modern DevOps Technologies
Introduction to  Modern DevOps TechnologiesIntroduction to  Modern DevOps Technologies
Introduction to Modern DevOps Technologies
 
Flink Forward San Francisco 2018: Gregory Fee - "Bootstrapping State In Apach...
Flink Forward San Francisco 2018: Gregory Fee - "Bootstrapping State In Apach...Flink Forward San Francisco 2018: Gregory Fee - "Bootstrapping State In Apach...
Flink Forward San Francisco 2018: Gregory Fee - "Bootstrapping State In Apach...
 
Introduction to Kafka connect
Introduction to Kafka connectIntroduction to Kafka connect
Introduction to Kafka connect
 
Creating Connector to Bridge the Worlds of Kafka and gRPC at Wework (Anoop Di...
Creating Connector to Bridge the Worlds of Kafka and gRPC at Wework (Anoop Di...Creating Connector to Bridge the Worlds of Kafka and gRPC at Wework (Anoop Di...
Creating Connector to Bridge the Worlds of Kafka and gRPC at Wework (Anoop Di...
 
Flink Forward San Francisco 2018: Dave Torok & Sameer Wadkar - "Embedding Fl...
Flink Forward San Francisco 2018:  Dave Torok & Sameer Wadkar - "Embedding Fl...Flink Forward San Francisco 2018:  Dave Torok & Sameer Wadkar - "Embedding Fl...
Flink Forward San Francisco 2018: Dave Torok & Sameer Wadkar - "Embedding Fl...
 
The journey of Moving from AWS ELK to GCP Data Pipeline
The journey of Moving from AWS ELK to GCP Data PipelineThe journey of Moving from AWS ELK to GCP Data Pipeline
The journey of Moving from AWS ELK to GCP Data Pipeline
 
12 Factor App: Best Practices for JVM Deployment
12 Factor App: Best Practices for JVM Deployment12 Factor App: Best Practices for JVM Deployment
12 Factor App: Best Practices for JVM Deployment
 
Streaming with Spring Cloud Stream and Apache Kafka - Soby Chacko
Streaming with Spring Cloud Stream and Apache Kafka - Soby ChackoStreaming with Spring Cloud Stream and Apache Kafka - Soby Chacko
Streaming with Spring Cloud Stream and Apache Kafka - Soby Chacko
 
Spacecrafts Made Simple: How Loft Orbital Delivers Unparalleled Speed-to-Spac...
Spacecrafts Made Simple: How Loft Orbital Delivers Unparalleled Speed-to-Spac...Spacecrafts Made Simple: How Loft Orbital Delivers Unparalleled Speed-to-Spac...
Spacecrafts Made Simple: How Loft Orbital Delivers Unparalleled Speed-to-Spac...
 
Apache Flink @ Alibaba - Seattle Apache Flink Meetup
Apache Flink @ Alibaba - Seattle Apache Flink MeetupApache Flink @ Alibaba - Seattle Apache Flink Meetup
Apache Flink @ Alibaba - Seattle Apache Flink Meetup
 
Flink Forward San Francisco 2019: Apache Beam portability in the times of rea...
Flink Forward San Francisco 2019: Apache Beam portability in the times of rea...Flink Forward San Francisco 2019: Apache Beam portability in the times of rea...
Flink Forward San Francisco 2019: Apache Beam portability in the times of rea...
 
Riding the Streaming Wave DIY style
Riding the Streaming Wave  DIY styleRiding the Streaming Wave  DIY style
Riding the Streaming Wave DIY style
 
Setting Up InfluxDB for IoT by David G Simmons
Setting Up InfluxDB for IoT by David G SimmonsSetting Up InfluxDB for IoT by David G Simmons
Setting Up InfluxDB for IoT by David G Simmons
 
Synchronous Commands over Apache Kafka (Neil Buesing, Object Partners, Inc) K...
Synchronous Commands over Apache Kafka (Neil Buesing, Object Partners, Inc) K...Synchronous Commands over Apache Kafka (Neil Buesing, Object Partners, Inc) K...
Synchronous Commands over Apache Kafka (Neil Buesing, Object Partners, Inc) K...
 
Vyacheslav Zholudev – Flink, a Convenient Abstraction Layer for Yarn?
Vyacheslav Zholudev – Flink, a Convenient Abstraction Layer for Yarn?Vyacheslav Zholudev – Flink, a Convenient Abstraction Layer for Yarn?
Vyacheslav Zholudev – Flink, a Convenient Abstraction Layer for Yarn?
 
Deploying and Operating KSQL
Deploying and Operating KSQLDeploying and Operating KSQL
Deploying and Operating KSQL
 
Building your first aplication using Apache Apex
Building your first aplication using Apache ApexBuilding your first aplication using Apache Apex
Building your first aplication using Apache Apex
 

Similar to Introduction to Ruby Native Extensions and Foreign Function Interface

Developing Rich Internet Applications with Perl and JavaScript
Developing Rich Internet Applications with Perl and JavaScriptDeveloping Rich Internet Applications with Perl and JavaScript
Developing Rich Internet Applications with Perl and JavaScript
nohuhu
 
The future of server side JavaScript
The future of server side JavaScriptThe future of server side JavaScript
The future of server side JavaScript
Oleg Podsechin
 
Legacy of Void*
Legacy of Void*Legacy of Void*
Legacy of Void*
Adam Crain
 

Similar to Introduction to Ruby Native Extensions and Foreign Function Interface (20)

Extending Ruby using C++
Extending Ruby using C++Extending Ruby using C++
Extending Ruby using C++
 
carrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIcarrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-API
 
Concurrency in ruby
Concurrency in rubyConcurrency in ruby
Concurrency in ruby
 
Ruby confhighlights
Ruby confhighlightsRuby confhighlights
Ruby confhighlights
 
Advance Android Application Development
Advance Android Application DevelopmentAdvance Android Application Development
Advance Android Application Development
 
Writing a Gem with native extensions
Writing a Gem with native extensionsWriting a Gem with native extensions
Writing a Gem with native extensions
 
Mac ruby deployment
Mac ruby deploymentMac ruby deployment
Mac ruby deployment
 
From gcc to the autotools
From gcc to the autotoolsFrom gcc to the autotools
From gcc to the autotools
 
Ruby C extensions at the Ruby drink-up of Sophia, April 2012
Ruby C extensions at the Ruby drink-up of Sophia, April 2012Ruby C extensions at the Ruby drink-up of Sophia, April 2012
Ruby C extensions at the Ruby drink-up of Sophia, April 2012
 
Common Gateway Interface ppt
Common Gateway Interface pptCommon Gateway Interface ppt
Common Gateway Interface ppt
 
Where is my scalable API?
Where is my scalable API?Where is my scalable API?
Where is my scalable API?
 
Functional MCU programming
Functional MCU programmingFunctional MCU programming
Functional MCU programming
 
Developing Rich Internet Applications with Perl and JavaScript
Developing Rich Internet Applications with Perl and JavaScriptDeveloping Rich Internet Applications with Perl and JavaScript
Developing Rich Internet Applications with Perl and JavaScript
 
The future of server side JavaScript
The future of server side JavaScriptThe future of server side JavaScript
The future of server side JavaScript
 
Cgi
CgiCgi
Cgi
 
Get your teeth into Plack
Get your teeth into PlackGet your teeth into Plack
Get your teeth into Plack
 
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
 
Ruby on the server
Ruby on the serverRuby on the server
Ruby on the server
 
Legacy of Void*
Legacy of Void*Legacy of Void*
Legacy of Void*
 
Road to sbt 1.0: Paved with server (2015 Amsterdam)
Road to sbt 1.0: Paved with server (2015 Amsterdam)Road to sbt 1.0: Paved with server (2015 Amsterdam)
Road to sbt 1.0: Paved with server (2015 Amsterdam)
 

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Recently uploaded (20)

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

Introduction to Ruby Native Extensions and Foreign Function Interface

  • 1. Introduction to Ruby Native Extensions and Foreign Function Interface https://github.com/suhovius/ruby_c_experiments Oleksii Sukhovii
  • 2.
  • 3. In order to compile C code make and gcc (or clang for macOS) should be installed. At systems with the APT package manager: $ sudo apt install -y make gcc
  • 4. Native Extension ● C code that’s included inside the Ruby gem ● Calls the external components API ● Converts parameters and return values between the external library format and Ruby interpreter expectations ● Native Extension C code is directly executed by VM (MRI, YARV, etc)
  • 5. Why do we write C extensions? ● Ruby’s C APIs are bridge between the Ruby and C world ● High performing C code which is directly connected to Ruby code (No need to waste the time for data interchange between different processes or services) ● Integratoin with C libraries (nokogiri, mysql2)
  • 6. Why we do NOT write C extensions? ● 10x harder to write, maintain, and understand ● More issues to consider, such as memory management and type safety ● Ruby API is huge and largely undocumented ● Might require delving through the Ruby source code ● Ruby source uses some fairly sophisticated C
  • 7. Ruby Gem with Native C Extensions Compile the extension: rake compile:math_demo Use extension in the gems console: bin/console > MathDemo.c_pow(3, 2) => 9.0
  • 8. extconf.rb MakeMakefile https://www.rubydoc.info/stdlib/mkmf/Ma keMakefile - mkmf docs https://silverhammermba.github.io/embe rb/extend/ - docs https://makefiletutorial.com/ - Makefiles tutorial https://github.com/dmke/ktoblzcheck/blo b/master/ext/ktoblzcheck/extconf.rb - original extconf.rb file mkmf.rb is used by Ruby C extensions to generate a Makefile which will correctly compile and link the C extension to Ruby and a third-party library.
  • 10. Ruby C API ● #include <ruby.h> - header with Ruby C API Macros ● void Init_math_demo() - called when compiled extension file is required: require ‘math_demo/math_demo’ ● ID id_puts = rb_intern("puts") - type and method that converts C string to ruby symbol :puts ● Type VALUE represents Ruby Object within C ● void rb_define_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc); ● NUM2DBL(rb_value), DBL2NUM(c_value) - few of many Ruby to C and C to Ruby conversion macroses
  • 11. Ruby Native C Useful Links https://blog.peterzhu.ca/ruby-c-ext/ - A Rubyist's Walk Along the C-side http://silverhammermba.github.io/emberb/c/ - The Ruby C API https://github.com/andremedeiros/ruby-c-cheat-sheet - Ruby C Cheat Sheet https://github.com/ruby/ruby/blob/master/doc/extension.rdoc - Official documentation https://github.com/miyucy/sophia-ruby/blob/master/ext/sophia.c - Good practical usage example https://dev.to/vinistock/creating-ruby-native-extensions-kg1 - Creating Ruby native extensions http://aaronbedra.com/extending-ruby/ - libxml example http://clalance.blogspot.com/2011/01/writing-ruby-extensions-in-c-part-1.html - In-depth series on Ruby extensions in C https://ruby-doc.com/docs/ProgrammingRuby/html/ext_ruby.html - Extending Ruby
  • 12. ● https://github.com/seattlerb/rubyinline - gem ● Allows to write foreign code within ruby code ● Automatically determines if the code has changed and builds it only when necessary ● Extensions are then automatically loaded into the class/module that defines it ● Code is being compiled on the fly, so first run might be slow, then it is cached for next call ● Not supporting alternative names for data types at called function signature (Ignores their definitions in the headers, maybe requires some unknown magic to fix it) Ruby Inline
  • 13. Foreign Function Interface (Ruby-FFI gem) ● Loading dynamically-linked native libraries programmatically ● Binding functions within libraries ● Calling these functions from Ruby code ● Works without changes on CRuby (MRI), JRuby, Rubinius and TruffleRuby Requirements C compiler (Xcode, gcc, clang) libffi library and dev headers (libffi- dev or libffi-devel packages) https://github.com/ffi/ffi/wiki/why-use-ffi Features ● Intuitive DSL ● Supports all C native types ● C structs (also nested), enums and global variables ● Callbacks from C to Ruby ● Automatic garbage collection of native memory
  • 14. FFI Basic Usage attach_function ● First argument* gives the name we want to use when calling the method, - so snake-case 🐍 instead of camel-case 🐫 ● Second argument is the actual name of the function in the C library so FFI can find it ● Third argument is an array of types which informs FFI of the argument types we expect to be passing in (in order) ● The last argument is the expected type of the return value ffi_lib ● loads ‘libh3’ library ● accepts names of or paths to libraries to load
  • 15. FFI Useful Links ● https://github.com/ffi/ffi gem docs and wiki https://github.com/ffi/ffi/wiki ● https://www.rubydoc.info/github/ffi/ffi - ruby doc ● https://www.rubyguides.com/2019/05/ruby-ffi/ - Play Media Files with VLC and FFI ● https://stuart.com/blog/tech/ruby-bindings-extensions/ - FFI examle with Uber H3 library https://github.com/StuartApp/h3_ruby - ruby gem that connects with H3 library via FFI ● https://github.com/hybridgroup/rubyserial/blob/master/lib/rubyserial/linux_constants.rb - usage example with method attachment and C structs ● https://www.varvet.com/blog/advanced-topics-in-ruby-ffi/ - Advanced Topics ● https://spin.atomicobject.com/2013/02/15/ffi-foreign-function-interfaces/ - Foreign Function Interfaces for Fun & Industry
  • 16. Fiddle ● Added to Ruby's standard library in 1.9.x ● Fiddle is an extension to translate a foreign function interface (FFI) with ruby. ● Wraps libffi, a popular C library which provides a portable interface that allows code written in one language to call code written in another language ● Allows to inspect and alter the ruby interpreter as it runs
  • 17. Fiddle Usage Fiddle::Importer - A DSL that provides the means to dynamically load libraries and build modules around them including calling extern functions within the C library that has been loaded. https://ruby- doc.org/stdlib-2.5.3/libdoc/fiddle/rdoc/Fiddle/Importer.html
  • 18. Fiddle Useful Links ● https://www.honeybadger.io/blog/use-any-c-library-from-ruby-via-fiddle-the-ruby-standard- librarys-best-kept-secret/ - Use any C library from Ruby via Fiddle ● https://medium.com/@astantona/fiddling-with-rubys-fiddle-39f991dd0565 - Fiddling with Ruby’s Fiddle ● https://stackoverflow.com/questions/50785133/ruby-fiddle-define-struct - Ruby Fiddle Structs ● https://ruby-doc.org/stdlib-3.0.2/libdoc/fiddle/rdoc/Fiddle.html rDoc ● https://github.com/ruby/fiddle Gem
  • 19. Performance Benchmarks For Levenshtein distance algorithm Approach Iterations Per Second Elapsed time Memory Allocations Native C Extension (Ruby C APi) 1544254.8 i/s 0.000009 40 allocated Ruby Inline 1342312.5 i/s - 1.15x (± 0.00) slower 0.000011 80 allocated - 2.00x more FFI 1291394.3 i/s - 1.20x (± 0.00) slower 0.000013 40 (same as Native C) Fiddle 269478.0 i/s - 5.73x (± 0.00) slower 0.000025 317 allocated - 7.92x more Ruby, RubyGems algorithm 111615.4 i/s - 13.84x (± 0.00) slower 0.000126 528 allocated - 13.20x more
  • 20. Usability Comparison Approach Pros Cons Native C Extension (Ruby C APi) Huge Performance as it is the most close to Native C as Ruby can get to Usage complexity, low level coding (memory management, type safety), boilerplate code, not fully documented Ruby Inline Simplest usage for Native C. Just copy-paste the C code into Ruby and run it inline. No need to compile code separately. 1.15x times slower and 2x times allocates more memory than native C Compilation at runtime Not working with dynamically linked libraries FFI Easy to use, automatic garbage collection, customizable, good level of control, good documentation. 1.2x times slower than native C Not ruby stdlib gem as Fiddle Fiddle Simplest FFI, almost verbatim mapping of the C code to Ruby. Ruby stdlib gem. 4.5x times slower and 7.92x times allocates more memory than FFI Ruby Easy and comfortable for Rubyists. The most programmer friendly solution 13.84x times slower and 13.20x more memory usage as it can not compete with Native C
  • 21. I need C code in Ruby (For Performance or External C Library Integration) Yes No Super Fast! Memory Efficient! Do not care about complexity! Fast and Easy Native Ruby C API FFI Which one to choose? Easier / No Dependencies (Ruby Stdlib) / Slower Fiddle Few lines of C Code Ruby Inline Do you really need C for so few lines of code? Yes No Faster and Memory Efficient Ruby
  • 22. ● https://www.learn-c.org/ Learn C ● https://www.tutorialspoint.com/cprogramming/index.htm C Tutorial ● https://github.com/oz123/awesome-c Some C Libraries to practice Ruby integration ● https://vtd-xml.sourceforge.io/ Good C Library to practice Ruby Integration, Especially this https://vtd-xml.sourceforge.io/codeSample/cs4.html example ● https://riptutorial.com/ruby/example/17682/working-with-c-structs Working with C Structs via Ruby Native C API More of the Useful Links! :)

Editor's Notes

  1. Папка с картинками-заглушками на все случаи жизни: https://drive.google.com/open?id=1YYMzg9hY1h-4b2DpeUVQivZvZ6eZvy5m
  2. Папка с картинками-заглушками на все случаи жизни: https://drive.google.com/open?id=1YYMzg9hY1h-4b2DpeUVQivZvZ6eZvy5m
  3. Папка с картинками-заглушками на все случаи жизни: https://drive.google.com/open?id=1YYMzg9hY1h-4b2DpeUVQivZvZ6eZvy5m
  4. Папка с картинками-заглушками на все случаи жизни: https://drive.google.com/open?id=1YYMzg9hY1h-4b2DpeUVQivZvZ6eZvy5m
  5. Папка с картинками-заглушками на все случаи жизни: https://drive.google.com/open?id=1YYMzg9hY1h-4b2DpeUVQivZvZ6eZvy5m
  6. Папка с картинками-заглушками на все случаи жизни: https://drive.google.com/open?id=1YYMzg9hY1h-4b2DpeUVQivZvZ6eZvy5m
  7. Папка с картинками-заглушками на все случаи жизни: https://drive.google.com/open?id=1YYMzg9hY1h-4b2DpeUVQivZvZ6eZvy5m
  8. Папка с картинками-заглушками на все случаи жизни: https://drive.google.com/open?id=1YYMzg9hY1h-4b2DpeUVQivZvZ6eZvy5m
  9. Папка с картинками-заглушками на все случаи жизни: https://drive.google.com/open?id=1YYMzg9hY1h-4b2DpeUVQivZvZ6eZvy5m
  10. Папка с картинками-заглушками на все случаи жизни: https://drive.google.com/open?id=1YYMzg9hY1h-4b2DpeUVQivZvZ6eZvy5m