英文:
Pass String to a method that accepts an UnsafeRawPointer parameter
问题
每次执行processUnsafeRawPointer(key)
时,打印的结果为什么不同?
将String
直接传递给接受UnsafeRawPointer
参数的方法时会发生什么?
var key = "Key"
func jump() {
print("\n测试UnsafeRawPointer")
processUnsafeRawPointer(key)
processUnsafeRawPointer(&key)
}
func processUnsafeRawPointer(_ key: UnsafeRawPointer) {
print(key)
}
public static func main() {
jump()
jump()
jump()
}
控制台输出:
测试UnsafeRawPointer
0x0000600000c104a0
0x000000010000d3c0
测试UnsafeRawPointer
0x0000600000c104a0
0x000000010000d3c0
测试UnsafeRawPointer
0x0000600000c18020
0x000000010000d3c0
英文:
Does anyone know why every time processUnsafeRawPointer(key)
is executed, the printed result is different?
What happens when passing String
directly to a method that accepts an UnsafeRawPointer
parameter?
var key = "Key"
func jump() {
print("\ntest UnsafeRowPointer")
processUnsafeRawPointer(key)
processUnsafeRawPointer(&key)
}
func processUnsafeRawPointer(_ key: UnsafeRawPointer) {
print(key)
}
public static func main() {
jump()
jump()
jump()
}
Console:
test UnsafeRowPointer
0x0000600000c104a0
0x000000010000d3c0
test UnsafeRowPointer
0x0000600000c104a0
0x000000010000d3c0
test UnsafeRowPointer
0x0000600000c18020
0x000000010000d3c0
答案1
得分: 2
以下是翻译好的部分:
> 当您调用声明为接受UnsafePointer<Type>
参数的函数时,可以传递以下任何一种:
- 如果Type是
Int8
或UInt8
,则可以传递String
值。字符串将自动转换为以零结尾的UTF8缓冲区,并将该缓冲区的指针传递给函数。 - 包含可变变量、属性或下标引用的in-out表达式,其类型为
Type
,将作为指向左侧标识符地址的指针传递。
当您调用接受UnsafeRawPointer
参数的函数时,可以传递与UnsafePointer<Type>
相同的操作数,但Type
可以是任何类型。
processUnsafeRawPointer(key)
是“String
值”情况。将创建一个缓冲区。此缓冲区在内存中的某个位置分配,并且不必每次都在相同位置。
processUnsafeRawPointer(&key)
是“in-out表达式”情况。由于key
是一个var
,这只会传递var
的位置,而不会执行其他操作。
英文:
What actually happens is documented here:
> When you call a function that is declared as taking an
> UnsafePointer<Type>
argument, you can pass any of the following:
>
> ...
>
> - A String
value, if Type is Int8
or UInt8
. The string is automatically converted to UTF8 in a zero-terminated buffer, and a
> pointer to that buffer is passed to the function.
> - An in-out expression that contains a mutable variable, property, or subscript reference of type Type
, which is passed as a pointer to
> the address of the left-hand side identifier.
>
> ...
>
> When you call a function that takes an UnsafeRawPointer
argument,
> you can pass the same operands as UnsafePointer<Type>
, but with any
> type as Type
.
processUnsafeRawPointer(key)
is the "a String
value" case. A buffer will be created. This buffer is allocated somewhere in memory, and doesn't have to be the same location every time.
processUnsafeRawPointer(&key)
is the "an in-out expression" case. Since key
is a var
, this will just pass the location of the var
, without doing anything else.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论