将 UnsafeMutablePointer<Void> 指向自身
Point an UnsafeMutablePointer<Void> to itself
在C中,指针指向分配给指针的内存位置是有效的:
static void * SomeContext = &SomeContext;
我已经看到它在 Objective-C 代码库中与 KVO 一起使用,通过将此指针用作 observeValueForKeyPath:ofObject:change:context:
.
中的 context
是否可以将指针指向在 Swift 中为该指针分配的内存 space,或者手动为指针分配内存?在初始化期间试图将指针指向自身的内存值会导致错误(如预期):
var somePointer: UnsafeMutablePointer<Void> = &somePointer // Error: Variable used within its own initial value
CMutableVoidPointer
不再存在于语言中,初始化指针 (UnsafeMutablePointer<Void>()
) 已弃用,只需将指针设置为 nil
.
可能是这样的:
var ptr = malloc(sizeof(UnsafeMutablePointer<Void>))
ptr = &ptr // Error: error: cannot assign value of type 'inout UnsafeMutablePointer<Void>' (aka 'inout UnsafeMutablePointer<()>') to type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')
在 Swift 3:
var somePointer = UnsafeMutableRawPointer(bitPattern: 1)!
somePointer = UnsafeMutableRawPointer(mutating: &somePointer)
print(somePointer)
print(somePointer.load(as: UnsafeMutableRawPointer.self))
// Output of both should be the same.
Swift 2:
Use withUnsafePointer
获取指向变量的指针。然后将其分配给自己。
var somePointer: UnsafeMutablePointer<Void> = nil
withUnsafePointer(&somePointer) { somePointer = UnsafeMutablePointer([=11=]) }
在C中,指针指向分配给指针的内存位置是有效的:
static void * SomeContext = &SomeContext;
我已经看到它在 Objective-C 代码库中与 KVO 一起使用,通过将此指针用作 observeValueForKeyPath:ofObject:change:context:
.
context
是否可以将指针指向在 Swift 中为该指针分配的内存 space,或者手动为指针分配内存?在初始化期间试图将指针指向自身的内存值会导致错误(如预期):
var somePointer: UnsafeMutablePointer<Void> = &somePointer // Error: Variable used within its own initial value
CMutableVoidPointer
不再存在于语言中,初始化指针 (UnsafeMutablePointer<Void>()
) 已弃用,只需将指针设置为 nil
.
可能是这样的:
var ptr = malloc(sizeof(UnsafeMutablePointer<Void>))
ptr = &ptr // Error: error: cannot assign value of type 'inout UnsafeMutablePointer<Void>' (aka 'inout UnsafeMutablePointer<()>') to type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')
在 Swift 3:
var somePointer = UnsafeMutableRawPointer(bitPattern: 1)!
somePointer = UnsafeMutableRawPointer(mutating: &somePointer)
print(somePointer)
print(somePointer.load(as: UnsafeMutableRawPointer.self))
// Output of both should be the same.
Swift 2:
Use withUnsafePointer
获取指向变量的指针。然后将其分配给自己。
var somePointer: UnsafeMutablePointer<Void> = nil
withUnsafePointer(&somePointer) { somePointer = UnsafeMutablePointer([=11=]) }