I will briefly explain how to call a library written in C from Ruby. There are some sites that explain it, including the official one, but I wanted you to tell me more simply ...
https://ruby-doc.org/core-2.5.3/doc/extension_ja_rdoc.html https://qiita.com/suketa/items/ab6b88093de4a54b3b06
https://github.com/hakua-doublemoon/rb_ext_hello
As shown in the sample C code shown above. Define a class with an Init function (you can also define a module), create a method definition and the corresponding function. In the method, it is written at the beginning of the official document, but since the usage of types is different between Ruby and C, use a dedicated function when interacting with each other. In other words, it looks like the following.
hello.c
return rb_str_new("Hello World", 11);
I don't write the Makefile myself. You can make it by creating extconf.rb and then ruby extconf.rb
. This is also included in the sample.
(I think it can be executed if Ruby is installed, but maybe ruby-dev
is necessary?)
The module name (class name?) Specified by create_makefile ()
does not have to match the case of the file name. So I used hello.c
in lowercase for the C file name and Hello
for the class name like a type name.
ruby extconf.rb
and when the Makefile is created, make
.
By the way, even if you write extconf.rb before creating the C file, you may get a Makefile that cannot be made.
Since it's a big deal, I'll write up to the point where I'll try it. I wrote it in the sample, but you can do it as follows.
require "./Hello"
hello = Hello::new
hello.methods
#=> [:say, :instance_variable_set, :instance_variable_defined?, ...
# ^There is a method I made here.
hello.say
#=> "Hello World"
hello.say.class
#=> String
At first, I thought that I should execute the program made in C as a command from Ruby, but I learned that the overhead of popen is quite large, so I decided to make a shared library. If you popopen in a single shot, you won't see much overhead. However, I think that there will be a big difference depending on whether you execute it with popen about 1000 times or load the library and execute it. (I think it depends on the execution environment) The following is the result of the experiment.
The result of executing the C program to Hello World 1000 times with popen:
user system total real
Case01 0.125000 0.296875 2.625000 ( 11.617396)
The result of executing the library I made this time 1000 times:
user system total real
Case01 0.000000 0.000000 0.000000 ( 0.000436)
1000 libraries I made this time*Result of running 1000 times:
user system total real
Case01 0.109375 0.015625 0.125000 ( 0.130412)
As a person who uses Ruby, you may try to find the cause of the heavy pop of Ruby ....
Recommended Posts