gem ffi を使って Ruby から Go の関数を実行
下記を参考にしたが、いろいろエラーが出て実行できなかった。
http://cluex-developers.hateblo.jp/entry/2018/06/27/172950
そもそも環境情報がかなり不足している。
筆者の環境
macOS High Sierra
Version 10.13.3
code:bash
$ ruby -v
ruby 2.5.0p0 (2017-12-25 revision 61468) x86_64-darwin17
code:bash
$ go version
go version go1.10.3 darwin/amd64
code:bash
$ gem list | grep ffi
ffi (1.9.25)
最初に遭遇したエラー
https://hub.docker.com/r/masaki1111/golang-vim-dev/ を使って Go をコンパイル。
Mac で実行。
code:bash
Could not open library './sum.so': dlopen(./sum.so, 5): no suitable image found. Did find: (LoadError)
./sum.so: unknown file type, first eight bytes: 0x7F 0x45 0x4C 0x46 0x02 0x01 0x01 0x00
https://github.com/ffi/ffi/wiki/Using-ruby-ffi-on-OsX-with-mixed-architectures,-universal-binaries.
上記によると、mixed architectures ( 32bit、64bit)が原因らしい。
Go のビルドは コンテナじゃなくて Mac ですることにした。
brew で Go をインストール。
次に遭遇したエラー
code:bash
`attach_function': Function 'sum' not found in ./sum.so (FFI::NotFoundError)
何回やっても出る。
いろいろサンプルをあたっているうちに以下の記事に出会った。
https://gist.github.com/Schweigert/385cd8e2267140674b6c4818d8f0c373
code:bash
$ go build -o my_lib.so -buildmode=c-shared my_file.go
なんと、微妙に build コマンドが違うじゃないか!
❌
code:bash
$ go build -buildmode=c-shared -o sum.so sum.go
Go のバージョンによるものらしい。
やっぱり環境情報大事。
成果物
https://github.com/m-maeda-ff/ruby-meets-go
参考
http://cluex-developers.hateblo.jp/entry/2018/06/27/172950
https://gist.github.com/Schweigert/385cd8e2267140674b6c4818d8f0c373
https://c7.se/go-and-ruby-ffi/
https://github.com/ffi/ffi/wiki/Using-ruby-ffi-on-OsX-with-mixed-architectures,-universal-binaries.
http://yamaimo.hatenablog.jp/entry/2015/05/21/200000