首先,您对ToPtr 的实现会引入不健全的代码。转载于此:
// code in italics is wrong
impl ToPtr for str {
fn to_ptr(&self) -> *const i8 {
CString::new(self).unwrap().as_ptr()
}
}
这会分配一个新的CString 并返回一个指向其内容的指针,但是CString 在to_ptr 返回时会被丢弃,所以这是一个悬空指针。 此指针的任何取消引用都是未定义的行为。documentation 对此有一个很大的警告,但这仍然是一个非常常见的错误。
从字符串文字生成*const c_char 的一种正确方法是b"string here\0".as_ptr() as *const c_char。该字符串以空值结尾并且没有悬空指针,因为字符串文字适用于整个程序。如果您有要转换的非常量字符串,您必须在使用 CString 时保持其活动状态,如下所示:
let s = "foo";
let cs = CString::new(s).unwrap(); // don't call .as_ptr(), so the CString stays alive
unsafe { some_c_function(cs.as_ptr()); }
// CString is dropped here, after we're done with it
除此之外:编辑器“建议”(我是 Stack Overflow 的新手,但评论而不是尝试重写我的答案似乎更有礼貌)上面的代码可以这样编写:
let s = "foo";
unsafe {
// due to temporary drop rules, the CString will be dropped at the end of the statement (the `;`)
some_c_function(CString::new(s).unwrap().as_ptr());
}
虽然这在技术上是正确的(最好的正确),但所涉及的“临时丢弃规则”是微妙的——这是因为 as_ptr 引用了 CString (实际上是&CStr,因为编译器将方法链更改为 CString::new(s).unwrap().deref().as_ptr()) 而不是消费它,而且因为我们只有一个 C要调用的函数。在编写不安全的代码时,我不喜欢依赖任何微妙或不明显的东西。
除此之外,我在你的代码中fixed that unsoundness(你的调用都使用字符串文字,所以我只是使用了上面的第一个策略)。我在 OSX 上得到这个输出:
0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 8, 1, 0, 0, 0, 0, 0, 0, 0
0, 0, 8, 2, 0, 0, 0, 0, 0, 0, 0
0, 0, 4, 3, 0, 0, 0, 0, 0, 0, 0
所以,这符合您的结果,对吧?我还编写了以下 C 程序:
#include <stdio.h>
#include <unistd.h>
int main() {
struct __sFILE *fp1 = fdopen(STDIN_FILENO, "r");
struct __sFILE *fp2 = fdopen(STDOUT_FILENO, "w");
struct __sFILE *fp3 = fdopen(STDERR_FILENO, "w");
struct __sFILE *passwd = fopen("/etc/passwd", "r");
printf("%i %i %i %i\n", fp1->_flags, fp2->_flags, fp3->_flags, passwd->_flags);
}
得到了输出:
4 8 8 4
这似乎证明了 Rust 的结果是正确的。 /usr/include/stdio.h 顶部有一条评论说:
/*
* The following always hold:
*
* if (_flags&(__SLBF|__SWR)) == (__SLBF|__SWR),
* _lbfsize is -_bf._size, else _lbfsize is 0
* if _flags&__SRD, _w is 0
* if _flags&__SWR, _r is 0
*/
然后查找这些常量:
#define __SLBF 0x0001 /* line buffered */
#define __SRD 0x0004 /* OK to read */
#define __SWR 0x0008 /* OK to write */
这似乎与我们得到的输出相匹配:4 表示以读取模式打开的文件,8 表示写入。那么这里有什么问题呢?