Skip to content

Instantly share code, notes, and snippets.

@wstucco
Last active October 12, 2015 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wstucco/7b0c424cf8dddbc8fd6a to your computer and use it in GitHub Desktop.
Save wstucco/7b0c424cf8dddbc8fd6a to your computer and use it in GitHub Desktop.
Writing Ruby Extensions in go
go build -buildmode=c-shared -o hello.so hello.go
# if no error is returned you can check that the shared library is exporting
# the right symbols by executing
# $ nm -gU ./hello.so | grep hello
# 0000000000002050 T __cgoexp_d4a435ec6890_hello_world
# 0000000000001ae0 T _hello_world <--- ALL SYSTEMS ARE GO
package main
/*
#include "ruby.h"
extern inline VALUE go_fast_blank(VALUE);
*/
import "C"
import (
"fmt"
"strings"
"unicode"
"unsafe"
)
//export go_fast_blank
func go_fast_blank(s C.VALUE) C.VALUE {
gs := C.GoString(C.rb_string_value_cstr(&s))
if gs == "" || strings.TrimLeftFunc(gs, unicode.IsSpace) == "" {
return C.Qtrue
}
return C.Qfalse
}
//export Init_go_fast_blank
func Init_go_fast_blank() {
fmt.Println("go_fast_blank init")
cs := C.CString("blank?")
defer C.free(unsafe.Pointer(cs))
C.rb_define_method(C.rb_cString, cs, (*[0]byte)(C.go_fast_blank), 0)
}
func main() {} // Required but ignored
package main
import "C"
import "fmt"
//export hello_world
func hello_world() {
fmt.Println("hello world")
}
func main() {} // Required but ignored
# copy and paste inside irb or other ruby repl
require 'ffi'
module Say
extend FFI::Library
ffi_lib './hello.so'
attach_function :hello_world, [], :void
end
Say.hello_world
# hello world
# => nil
/* Created by "go tool cgo" - DO NOT EDIT. */
/* package command-line-arguments */
/* Start of preamble from import "C" comments. */
#line 3 "/Users/name/path/ext/go_fast_blank/go_fast_blank.go"
#include "ruby.h"
extern inline VALUE go_fast_blank(VALUE);
/* End of preamble from import "C" comments. */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment