Rust如何返回大型类型(在优化之前)?

huangapple go评论52阅读模式
英文:

How does Rust return large types (before optimisation)?

问题

如下面的函数签名所示:

pub fn hash(input: &[u8]) -> [u8; 32]

这 32 个字节如何传递给调用函数?(在优化之前,可能会将一些部分放入寄存器中。)

可能的方式包括:

  • 在堆栈上,调用函数必须将它们复制到自己堆栈帧中预先分配的空间中。
  • 在堆上,通过在调用函数中插入生成的 free() 函数来释放它们。
  • 一些每个线程静态分配的缓冲区。

只是好奇,我不需要这个信息。答案可能会因体系结构而异。

英文:

With a function signature such as:

pub fn hash(input: &[u8]) -> [u8; 32]

how do those 32 bytes get passed to the calling function? (Before optimisation, which might place some parts in registers.)

Possibilities include:

  • On the stack, with the calling function having to copy them into pre-allocated space in its own stack frame.
  • On the heap, with a generated free() inserted into the calling function.
  • Some, per-thread, statically allocated buffer.

Just curious, I have no need for this information. The answer may differ by architectures.

答案1

得分: 5

没有复制或堆分配涉及。

调用者函数在其堆栈上为值分配空间。被调用者接另一个隐藏参数,返回值的地址。它将值写入那里。调用者将其堆栈上分配的空间的地址作为隐藏参数的值传递。

当然,这一切都不是保证的。这只是目前它偶然发生的方式。

英文:

There is neither a copy nor a heap allocation involved.

The caller function allocates space for the value on its stack. The callee takes an additional hidden parameter, the address of the return value. It writes the value there. The caller passes the address of the allocated space on its stack as the value for the hidden parameter.

Of course, none of that is guaranteed. This is just how it happens to work right now.

huangapple
  • 本文由 发表于 2023年7月18日 15:44:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710530.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定