I'm trying to understand the use of pointers in Swift, in particular: Unsafe[Mutable]Pointer
and UnsafeRaw[Mutable]Pointer
. I have several questions on the subject.
Is UnsafePointer <T>
equal to const T * Pointer
in ? and UnsafeMutablePointer <T>
is equal to T * Pointer
in C?
What is the difference between Unsafe[Mutable]Pointer
and UnsafeRaw[Mutable]Pointer
?
Why does this compile
func receive(pointer: UnsafePointer<Int> ) {
print("param value is: \(pointer.pointee)")
}
var a: Int = 1
receive(pointer: &a) // prints 1
but this gives me an error?
var a: Int = 1
var pointer: UnsafePointer<Int> = &a // error : Cannot pass immutable value of type 'Int' as inout argument
Swift's typed pointers give you direct access to memory, but only within the confines of type safety. You can't have two typed pointers to the same memory that disagree on the type. So, if your goal is to reinterpret bytes of memory as different types, then you need use a lower-level API.
UnsafePointer provides no automated memory management or alignment guarantees. You are responsible for handling the life cycle of any memory you work with through unsafe pointers to avoid leaks or undefined behavior. Memory that you manually manage can be either untyped or bound to a specific type.
Opaque pointers are used to represent C pointers to types that cannot be represented in Swift, such as incomplete struct types.
Go unsafe pointers mean the types whose underlying types are unsafe. Pointer . The zero values of unsafe pointers are also represented with the predeclared identifier nil . Before Go 1.17, the unsafe standard package has already provided three functions.
- Is
UnsafePointer <T>
equal toconst T * Pointer
in ? andUnsafeMutablePointer <T>
is equal toT * Pointer
in C?
Well, use a bridging header in a Swift app to see how the C pointers are bridged:
const int *myInt;
int *myOtherInt;
bridges to
var myInt: UnsafePointer<Int32>!
var myOtherInt: UnsafeMutablePointer<Int32>!
- What is the difference between
Unsafe[Mutable]Pointer
andUnsafeRaw[Mutable]Pointer
?
Swift 3 added a UnsafeRawPointer API to replace the Unsafe[Mutable]Pointer<Void>
type. Conversion between pointers of a different type is no longer allowed in Swift. Instead, the API provides interfaces (.assumingMemoryBound(to:)
or .bindMemory(to:capacity:)
) to bind memory to a type.
With regard to question 3, the ampersand means that the variable is inout
. I don't believe you can declare a variable as inout
unless it is being used by a function that directly modifies the underlying memory, but I'll let the experts correct me. Instead, use withUnsafePointer
.
Thanks to Martin's helpful comment, this syntax was never valid in Swift, and there is no safe way to create "free pointers" to Swift variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With