Use GoLang code in Ruby

Captain's log, stardate 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

Separated at birth from his brother Javier, he has now reunited with his frontend counterpart. If they should ever decide to merge in real life, they would become the ultimate full-stack developer every company wants to hire.

comments powered by Disqus

You're one step away from meeting your best partner in business.

Hire Us