1

灵感来自 Carol Goulding 关于“Rust Out Your C”的演讲和我阅读的一篇关于将 C 移植到 Rust 函数的文章。

如果我有一个由 3 个函数组成的程序一个接一个地调用:

1 (C) --> 2 (C) --> 3 (C)

并将第二个函数替​​换为静态链接的 Rust 函数,因此流程变为:

1 (C) --> 2 ( R ) --> 3 (C)

函数 2 中的代码现在是内存和/或类型安全吗?它是否在安全方面获得了任何额外的、有益的特性?

4

2 回答 2

3

Yes. And no. It depends.

  1. First of, the C code in functions 1 and 3 will not be affected in any way, and will be just as unsafe (per Rust's definition as unsafe) as any C.

  2. The code in function 2 will however benefit from Rust safety. Its implementation can be considered safer.

    However, you'll need some glue between your C and Rust. Rust safety mostly come from its type system, and C type system is quite poor in comparison. You'll need to properly call your Rust function from your C function and C function from your Rust function. C is mostly unaware of Rust, so this needs to be done on the Rust side. While there are tools and crates to help with FFI, you always have to assume at some point that the C is correct, as a bug in the C could manifest even in (safe) Rust. Moreover calling a C function from Rust always requires unsafe, and a Rust function called from C will often have some unsafe too. FFI is easy to get wrong: Wrong size of parameters, bad alignments, bad ABI, use of freed memory are all more likely at a language barrier and are all very unsafe.

于 2020-07-26T12:10:41.750 回答
0

不,嵌入到 C 代码中并不能使您的代码安全。你可能会在 Rust 部分获得生命周期检查,但前提是入口和出口被正确注释;例如,如果您的代码返回一个拥有的引用,但 C 代码希望它被借用,那么您仍然有内存泄漏。Rust 代码本身也可能不安全;Rust 编译器具有比 C 编译器更严格地帮助您跟踪内存和类型的工具,但它不会强迫您使用这些工具。它只会让编写有风险的代码来鼓励安全代码变得更加尴尬。

于 2020-07-26T12:10:56.947 回答