ffiex icon indicating copy to clipboard operation
ffiex copied to clipboard

call function in go binary

Open umegaya opened this issue 10 years ago • 0 comments

in these day, many good system software start to be written in go, such as etcd or serf. if such a trend keep on going in future, enable to call go function from luaJIT, may useful like:

//lib.go
//export double_fn
func double_fn(float64 in) float64 {
  return in * 2
}
local ffi = require 'ffiex'
require 'ffiex.go' --> should be optional
ffi.godef("path/to/lib.go")
local GO = ffi.gload("golib") --> contains built lib.go.
local f = GO.double_fn(ffi.new("GoFloat64", 1.0))
print(f) --> 2.0

probably luaJIT cannot get along with some feature of go like channel or goroutine without modification of luaJIT itself, but just call some go function and receive result still useful, I think.

with https://codereview.appspot.com/9733044/ , seems it already works, (I know that gccgo can do this, but it will require re-build go code in most case, so its not handy like current luaJIT FFI) I tried that but unfortunately, current go's -shared option cannot create the one which is loadable from luaJIT, but at least it contains mach-o-x86-64 format part in OSX go build.

dokyougemusu-no-MacBook-Pro:go iyatomi$ cat src/github.com/umegaya/math/sqrt.go 
// Package newmath is a trivial example package.
package math

/*
extern int foo(float x);
*/
import "C"

//export Sqrt
func Sqrt(x float64) float64 {
    z := 1.0
    for i := 0; i < 1000; i++ {
        z -= (z*z - x) / (2 * z)
    }
    return z
}
dokyougemusu-no-MacBook-Pro:go iyatomi$ go install -ldflags '-shared' github.com/umegaya/math
dokyougemusu-no-MacBook-Pro:go iyatomi$ gobjdump -aD pkg/darwin_amd64/github.com/umegaya/math.a 
書庫 pkg/darwin_amd64/github.com/umegaya/math.a 内:
gobjdump: __.GOSYMDEF: ファイル形式が認識できません
gobjdump: __.PKGDEF: ファイル形式が認識できません
gobjdump: _go_.6: ファイル形式が認識できません
gobjdump: _cgo_import.6: ファイル形式が認識できません
gobjdump: _cgo_defun.6: ファイル形式が認識できません

_all.o:     ファイル形式 mach-o-x86-64
rw-r--r-- 0/0   1120 Jan  1 09:00 1970 _all.o

<<...snip...>>>

セクション .text の逆アセンブル:

0000000000000000 <_Sqrt>:
   0:   55                      push   %rbp
   1:   48 89 e5                mov    %rsp,%rbp
   4:   48 83 ec 10             sub    $0x10,%rsp
   8:   f2 0f 11 45 f0          movsd  %xmm0,-0x10(%rbp)
   d:   48 8b 3d 00 00 00 00    mov    0x0(%rip),%rdi        # 14 <_Sqrt+0x14>
  14:   48 8d 75 f0             lea    -0x10(%rbp),%rsi
  18:   ba 10 00 00 00          mov    $0x10,%edx
  1d:   e8 00 00 00 00          callq  22 <_Sqrt+0x22>
  22:   f2 0f 10 45 f8          movsd  -0x8(%rbp),%xmm0
  27:   48 83 c4 10             add    $0x10,%rsp
  2b:   5d                      pop    %rbp
  2c:   c3                      retq   

umegaya avatar May 30 '14 05:05 umegaya