是否有一些关于如何在 Go 中为 Ruby 编写扩展的教程或实践类(class)?
最佳答案
Go 1.5 增加了对构建可从 C 调用的共享库的支持(因此从 Ruby 通过 FFI)。这使得该过程比 1.5 之前的版本更容易(当需要编写 C 粘合层时),并且 Go 运行时现在可用,这使得它在现实生活中真正有用(以前不可能使用 goroutines 和内存分配,因为它们需要 Go 运行时,如果 Go 不是主要入口点,则该运行时不可用)。
goFuncs.go:
package main
import "C"
//export GoAdd
func GoAdd(a, b C.int) C.int {
return a + b
}
func main() {} // Required but ignored
请注意,每个导出的函数都需要 //export GoAdd
注释; export
后面的符号是函数的导出方式。
goFromRuby.rb:
require 'ffi'
module GoFuncs
extend FFI::Library
ffi_lib './goFuncs.so'
attach_function :GoAdd, [:int, :int], :int
end
puts GoFuncs.GoAdd(41, 1)
库是用以下方式构建的:
go build -buildmode=c-shared -o goFuncs.so goFuncs.go
运行 Ruby 脚本会产生:
42
关于ruby - 在 Go (golang) 中编写一个 Ruby 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15879993/