在C中,指针指向分配给指针的内存位置是有效的:
static void * SomeContext = &SomeContext;
我已经在使用此指针作为context
中的observeValueForKeyPath:ofObject:change:context:
的KVO的Objective-C代码库中看到过这种情况。
是否可以指向指向Swift中为该指针分配的内存空间的指针,还是手动为指针分配内存?在初始化期间尝试将指针指向其自身的内存值会导致错误(如预期的那样):
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<()>')
答案 0 :(得分:3)
在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.
斯威夫特2:
Use withUnsafePointer
获取指向变量的指针。然后将其分配给自己。
var somePointer: UnsafeMutablePointer<Void> = nil
withUnsafePointer(&somePointer) { somePointer = UnsafeMutablePointer($0) }