Use GoLang code in Ruby

Diario del capitán, fecha estelar d297.y40/AB

GoLang has the option to create shared libraries in C, and in this post I will show you how to do it.

Screens with code - Photo by Fotis Fotopoulos

Shared libraries are native code files that have a direct interface with the C compiler. You can import them into a Ruby file as a module and use its functions.

go build [OUTPUT_C_FILE] -buildmode=c-shared [IMPUT_GO_FILE]

Here's an example of how to do it:

// my_file.go
package main

import "C"

//export my_add
func my_add(a, b C.int) C.int {
    return a + b
}

// This is necessary for the compiler.
// You can add something that will be executed when engaging your library to the interpreter.
func main() {}

Then, you have to execute the build command to create the C shared library.

go build -o my_lib.so -buildmode=c-shared my_file.go

Now, we are ready to import the C library into a Ruby file.

# shared_c_lib.rb

require 'ffi'

module Foo
  extend FFI::Library
  ffi_lib './my_lib.so'

  attach_function :my_add, [:int, :int], :int
end

puts Foo.my_add(2, 2)
# => 4

This process looks to have some limitations but it could help in processes where Ruby is a little slow, and it could help in using the best Go feature, its concurrency using Goroutines.

References

Juan Artero

Juan Artero

Separado de su hermano Javier al nacer, se ha reunido con alter-ego frontend en MarsBased. Si algún día decidieran fusionarse en la vida real, se convertirían en el desarrollador full-stack definitivo que toda compañía quiere contratar.

comments powered by Disqus

Estás a un paso de conocer a tu mejor socio.

Hablemos