在Go(golang)中编写Ruby扩展 [英] Writing a Ruby extension in Go (golang)

查看:123
本文介绍了在Go(golang)中编写Ruby扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一些关于如何在Go中为Ruby编写扩展的教程或实践课程?

Are there some tutorials or practical lessons on how to write an extension for Ruby in Go?

推荐答案

Go 1.5添加了对构建共享库的支持,该共享库可从C(因此可以通过FFI从Ruby)调用.这使该过程比1.5版之前的版本(需要编写C胶合层)更容易,并且Go运行时现在可以使用,这在现实生活中实际上是有用的(以前无法进行goroutine和内存分配,因为它们需要Go运行时,如果Go不是主要入口点,则该运行时将无法使用.

Go 1.5 added support for building shared libraries that are callable from C (and thus from Ruby via FFI). This makes the process easier than in pre-1.5 releases (when it was necessary to write the C glue layer), and the Go runtime is now usable, making this actually useful in real life (goroutines and memory allocations were not possible before, as they require the Go runtime, which was not useable if Go was not the main entry point).

goFuncs.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之后的符号是函数的导出方式.

Note that the //export GoAdd comment is required for each exported function; the symbol after export is how the function will be exported.

goFromRuby.rb:

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脚本会产生:

Running the Ruby script produces:


42

这篇关于在Go(golang)中编写Ruby扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆