Back

Use GoLang code in Ruby

Captain's log, stardate d297.y40/AB

golang Development Ruby Web development
Juan Artero
Full-stack developer
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

Share this post

Related Articles

Red keyboard

Building a Ruby CLI with Thor

We've written a Ruby CLI using Thor for a client project and we share everything we've learnt in this blog post!

Read full article
Lights

Speeding up views rendering in Rails 4

Here's some technical post for the Rails folks out there. If you're into performance optimisation, this is for you!

Read full article
Mesh

Query data from PostgreSQL to represent it in a time series graph

In this blog post, our CTO, Xavi, will show us how to query data from PostgreSQL to represent it in a time series graph.

Read full article