Go调用Rust方法及外部函数接口前置


Posted in Golang onJune 14, 2022

前言

近期 Rust 社区/团队有些变动,所以再一次将 Rust 拉到大多数人眼前。

我最近看到很多小伙伴说的话:

  • Rust 还值得学吗?社区是不是不稳定呀
  • Rust 和 Go 哪个好?
  • Rust 还值得学吗?

这些问题如果有人来问我,那我的回答是:

小孩子才做选择,我都要!

当然,关于 Rust 和 Go 的问题也不算新,比如之前的一条推文:

Go调用Rust方法及外部函数接口前置

我在本篇中就来介绍下如何用 Go 调用 Rust。

当然,这篇中我基本上不会去比较 Go 和 Rust 的功能,或者这种方式的性能之类的,Just for Fun

FFI 和 Binding

FFI (Foreign Function Interface) 翻译过来叫做外部函数接口(为了比较简单,下文中都将使用 FFI 指代)。最早来自于 Common Lisp 的规范,这是在 wiki 上写的,我并没有去考证。 不过我所使用过的绝大多数语言中都有 FFI 的概念/术语存在,比如:Python、Ruby, Haskell、Go、Rust、LuaJIT 等。

FFI 的作用简单来说就是允许一种语言去调用另一种语言,有时候我们也会用 Binding 来表示类似的能力。

在不同的语言中会有不同的实现,比如在 Go 中的 cgo , Python 中的 ctypes , Haskell 中的 CAPI (之前还有一个 ccall)等。 我个人感觉 Haskell 中用 FFI 相比其他语言要更简单&方便的多,不过这不是本篇的重点就不展开了。

在本文中,对于 Go 和 Rust 而言,它们的 FFI 需要与 C 语言对象进行通信,而这部分其实是由操作系统根据 API 中的调用约定来完成的。

我们来进入正题。

准备 Rust 示例程序

Rust 的安装和 Cargo 工具的基本使用,这里就不介绍了。大家可以去 Rust 的官网进行了解。

用 Cargo 创建项目

我们先准备一个目录用来放本次示例的代码。(我创建的目录叫做 go-rust )

然后使用 Rust 的 Cargo 工具创建一个名叫 rustdemo 的项目,这里由于我增加了 --lib 的选项,使用其内置的 library 模板。

➜  go-rust git:(master) ✗ mkdir lib && cd lib
➜  go-rust git:(master) ✗ cargo new --lib rustdemo
     Created library `rustdemo` package
➜  go-rust git:(master) ✗ tree rustdemo 
rustdemo
├── Cargo.toml
└── src
    └── lib.rs
1 directory, 2 files

准备 Rust 代码

extern crate libc;
use std::ffi::{CStr, CString};
#[no_mangle] 
pub extern "C" fn rustdemo(name: *const libc::c_char) -> *const libc::c_char {
    let cstr_name = unsafe { CStr::from_ptr(name) };
    let mut str_name = cstr_name.to_str().unwrap().to_string();
    println!("Rust get Input:  \"{}\"", str_name);
    let r_string: &str = " Rust say: Hello Go ";
    str_name.push_str(r_string);
    CString::new(str_name).unwrap().into_raw()
}

代码比较简单,Rust 暴露出来的函数名叫做 rustdemo ,接收一个外部的参数,并将其打印出来。之后从 Rust 这边再设置一个字符串。

CString::new(str_name).unwrap().into_raw() 被转换为原始指针,以便之后由 C 语言处理。

编译 Rust 代码

我们需要修改下 Cargo.toml 文件以便进行编译。注意,这里我们增加了 crate-type = ["cdylib"] 和 libc 。

[package]
name = "rustdemo"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
libc = "0.2"

然后进行编译

➜  rustdemo git:(master) ✗ cargo build --release
   Compiling rustdemo v0.1.0 (/home/tao/go/src/github.com/tao12345666333/go-rust/lib/rustdemo)
    Finished release [optimized] target(s) in 0.22s

查看生成的文件,这是一个 .so 文件(这是因为我在 Linux 环境下,你如果在其他系统环境下会不同)

➜  rustdemo git:(master) ✗ ls target/release/librustdemo.so 
target/release/librustdemo.so

准备 Go 代码

Go 环境的安装之类的这里也不再赘述了,继续在我们的 go-rust 目录操作即可。

编写 main.go

package main
/*
#cgo LDFLAGS: -L./lib -lrustdemo
#include <stdlib.h>
#include "./lib/rustdemo.h"
*/
import "C"
import (
	"fmt"
	"unsafe"
)
func main() {
	s := "Go say: Hello Rust"
	input := C.CString(s)
	defer C.free(unsafe.Pointer(input))
	o := C.rustdemo(input)
	output := C.GoString(o)
	fmt.Printf("%s\n", output)
}

在这里我们使用了 cgo ,在 import "C" 之前的注释内容是一种特殊的语法,这里是正常的 C 代码,其中需要声明使用到的头文件之类的。

下面的代码很简单,定义了一个字符串,传递给 rustdemo 函数,然后打印 C 处理后的字符串。

同时,为了能够让 Go 程序能正常调用 Rust 函数,这里我们还需要声明其头文件,在 lib/rustdemo.h 中写入如下内容:

char* rustdemo(char *name);

编译代码

在 Go 编译的时候,我们需要开启 CGO (默认都是开启的),同时需要链接到 Rust 构建出来的 rustdemo.so 文件,所以我们将该文件和它的头文件放到 lib 目录下。

➜  go-rust git:(master) ✗ cp lib/rustdemo/target/release/librustdemo.so lib

所以完整的目录结构就是:

➜  go-rust git:(master) ✗ tree -L 2 .
.
├── go.mod
├── lib
│   ├── librustdemo.so
│   ├── rustdemo
│   └── rustdemo.h
└── main.go
2 directories, 5 files

编译:

➜  go-rust git:(master) ✗ go build -o go-rust  -ldflags="-r ./lib" main.go
➜  go-rust git:(master) ✗ ./go-rust 
Rust get Input:  "Go say: Hello Rust"
Go say: Hello Rust Rust say: Hello Go

可以看到,第一行的输出是由 Go 传入了 Rust , 第二行中则是从 Rust 再传回 Go 的了。符合我们的预期。

总结

本篇介绍了如何使用 Go 与 Rust 进行结合,介绍了其前置关于 FFI 相关的知识,后续通过一个小的实践演示了其完整过程。 感兴趣的小伙伴可以自行实践下。

以上就是Go调用Rust方法及外部函数接口前置的详细内容,更多关于Go调用Rust外部函数接口前置的资料请关注三水点靠木其它相关文章!

Golang 相关文章推荐
Go语言操作数据库及其常规操作的示例代码
Apr 21 Golang
golang switch语句的灵活写法介绍
May 06 Golang
解决golang 关于全局变量的坑
May 06 Golang
聊聊golang中多个defer的执行顺序
May 08 Golang
Go 语言下基于Redis分布式锁的实现方式
Jun 28 Golang
golang 实用库gotable的具体使用
Jul 01 Golang
golang中的struct操作
Nov 11 Golang
深入理解go缓存库freecache的使用
Feb 15 Golang
Go归并排序算法的实现方法
Apr 06 Golang
Go并发4种方法简明讲解
Apr 06 Golang
Golang ort 中的sortInts 方法
Apr 24 Golang
详解Go语言中配置文件使用与日志配置
Jun 01 Golang
详解Go语言中配置文件使用与日志配置
Jun 01 #Golang
详解Go语言中Get/Post请求测试
Golang实现可重入锁的示例代码
May 25 #Golang
Go web入门Go pongo2模板引擎
May 20 #Golang
Go语言入门exec的基本使用
May 20 #Golang
Golang并发工具Singleflight
May 06 #Golang
深入理解 Golang 的字符串
May 04 #Golang
You might like
超级简单的发送邮件程序
2006/10/09 PHP
在同一窗体中使用PHP来处理多个提交任务
2008/05/08 PHP
浅析is_writable的php实现
2013/06/18 PHP
php旋转图片90度的方法
2013/11/07 PHP
PHP设置Cookie的HTTPONLY属性方法
2017/02/09 PHP
在php7中MongoDB实现模糊查询的方法详解
2017/05/03 PHP
PHP实现的一致性Hash算法详解【分布式算法】
2018/03/31 PHP
通过js脚本复制网页上的一个表格的不错实现方法
2006/12/29 Javascript
js GridView 实现自动计算操作代码
2009/03/25 Javascript
firefox和IE系列的相关区别整理 以备后用
2009/12/28 Javascript
自己写的兼容ie和ff的在线文本编辑器类似ewebeditor
2012/12/12 Javascript
如何阻止复制剪切和粘贴事件为了表单内容的安全
2013/05/23 Javascript
js中replace的用法总结
2013/12/27 Javascript
jQuery Real Person验证码插件防止表单自动提交
2015/11/06 Javascript
js中substr,substring,indexOf,lastIndexOf,split,replace的用法详解
2015/11/09 Javascript
Angularjs中三种数据的绑定策略(“@”,“=”,“&amp;”)
2016/12/23 Javascript
js装饰设计模式学习心得
2018/02/17 Javascript
jQuery中使用validate插件校验表单功能
2019/05/24 jQuery
vue+echarts实现动态折线图的方法与注意
2020/09/01 Javascript
[59:00]DOTA2-DPC中国联赛 正赛 Ehome vs PSG.LGD BO3 第一场 3月7日
2021/03/11 DOTA
决策树的python实现方法
2014/11/18 Python
python实现汉诺塔方法汇总
2016/07/25 Python
Python学习笔记之if语句的使用示例
2017/10/23 Python
python按行读取文件,去掉每行的换行符\n的实例
2018/04/19 Python
python实现n个数中选出m个数的方法
2018/11/13 Python
Pycharm取消py脚本中SQL识别的方法
2018/11/29 Python
Python 脚本拉取 Docker 镜像问题
2019/11/10 Python
python分别打包出32位和64位应用程序
2020/02/18 Python
用python实现前向分词最大匹配算法的示例代码
2020/08/06 Python
如何用Python 加密文件
2020/09/10 Python
Python+unittest+DDT实现数据驱动测试
2020/11/30 Python
Tostadora意大利:定制T恤
2019/04/08 全球购物
如何让Java程序执行效率更高
2014/06/25 面试题
Nginx 负载均衡是什么以及该如何配置
2021/03/31 Servers
mysql批量新增和存储的方法实例
2021/04/07 MySQL
在Django中使用MQTT的方法
2021/05/10 Python