Use GoLang code in Ruby

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

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