我发现以下代码可以编译并运行:func foo(p:UnsafePointer<UInt8>) { var p = p for p; p.memory != 0; p++ { print(String(format:"%2X", p.memory)) }}let str:String = "今日"foo(str)这将打印出来E4BB8AE697A5,并且是UTF8的有效表示形式今日据我所知,这是未记录的行为。从文档中:当一个函数被声明为带有UnsafePointer参数时,它可以接受以下任何一个:nil,作为空指针传递UnsafePointer,UnsafeMutablePointer或AutoreleasingUnsafeMutablePointer值,必要时将其转换为UnsafePointer一个In-out表达式,其操作数是Type类型的左值,作为左值的地址传递一个[Type]值,作为指向数组开头的指针传递,并在调用期间进行生命周期扩展在这种情况下,str不是他们。我想念什么吗?添加:如果参数类型是 UnsafePointer<UInt16>func foo(p:UnsafePointer<UInt16>) { var p = p for p; p.memory != 0; p++ { print(String(format:"%4X", p.memory)) }}let str:String = "今日"foo(str)// ^ 'String' is not convertible to 'UnsafePointer<UInt16>'即使内部String表示形式为UTF16let str = "今日"var p = UnsafePointer<UInt16>(str._core._baseAddress)for p; p.memory != 0; p++ { print(String(format:"%4X", p.memory)) // prints 4ECA65E5 which is UTF16 今日}
- 3 回答
- 0 关注
- 1107 浏览
添加回答
举报
0/150
提交
取消