Skip to content

Instantly share code, notes, and snippets.

@lsegal
Created August 31, 2016 22:11
Show Gist options
  • Save lsegal/587d0ca721679af7435421565d092bf9 to your computer and use it in GitHub Desktop.
Save lsegal/587d0ca721679af7435421565d092bf9 to your computer and use it in GitHub Desktop.
PS. Don't do this.
package main
// #cgo CFLAGS: -I /usr/include/ruby-2.1.0 -I /usr/include/x86_64-linux-gnu/ruby-2.1.0
// #cgo LDFLAGS: -lruby-2.1
// #include "ruby.h"
// extern VALUE rbGoFib(VALUE, VALUE);
import "C"
import "unsafe"
//export rbGoFib
func rbGoFib(self C.VALUE, n C.VALUE) C.VALUE {
return (C.VALUE)((fib(int(n)>>1) << 1) | 1)
}
func fib(n int) int {
if n < 2 {
return n
}
return fib(n-1) + fib(n-2)
}
//export Init_libfib
func Init_libfib() {
fib := C.rb_define_class(C.CString("Fib"), C.rb_cObject)
C.rb_define_method(fib, C.CString("fib"), (*[0]byte)(unsafe.Pointer(C.rbGoFib)), 1)
}
func main() {}
/*
require './libfib'
fib = Fib.new
p fib.fib(6)
# => 8
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment