On 1/6/22 09:06, Ladislav Slezák wrote:
Hi all!
You probably know the "ffi" gem (this is what you get if you google for "ruby ffi"), but I accidentally found out an alternative implementation called "fiddle". The advantage is that this library is a part of the Ruby stdlib so you do not need to depend on any external gem. And it is even included in Ruby 2.5, so it is already part of SLE15...
It also provides a simple wrapper for accessing the functions from Ruby similar to the ffi gem. I wrote a simple example which sorts strings using the current locale (that's not possible in standard Ruby) and uses the strcoll() glibc function.
The nice thing is that it can directly parse the C function signatures, so you can just use "man strcoll" and copy and paste the signature to Ruby:
dlload "libc.so.6" extern "int strcoll(char*, char*)"
...and that's it!
See the full example at https://github.com/lslezak/scripts/blob/master/misc/locale_sorter.rb
This might be useful if you ever need some low-level system call in Ruby.
Notes:
As this internally uses dlopen() for opening the *.so libraries then obviously you cannot use the constants and macros defined in the *.h header files. That might complicate things in some cases...
You might open also a C++ library, e.g. zypp = Fiddle.dlopen("libzypp.so") works fine, but the problem is that C++ uses method name mangling and working with objects would be difficult.
So in practice this is limited to some simple plain C libraries, but it still might be useful as you do not need to write any line of C code and you do not even need a compiler...
Ladislav
Very nice! Thanks a lot for sharing! Iván -- José Iván López González YaST Team at SUSE LINUX GmbH IRC: jilopez