Friday, January 6, 2017

Unsafe Swift: Using Pointers and Interacting With C

Ray Fix (via Greg Heo):

MemoryLayout<Type> is a generic type evaluated at compile time that determines the size, alignment and stride of each specified Type.

[…]

Unsafe Swift pointers use a very predictable naming scheme so that you know what the traits of the pointer are. Mutable or immutable, raw or typed, buffer style or not. In total there is a combination of eight of these.

[…]

This example is similar to the previous one, except that it first creates a raw pointer. The typed pointer is created by binding the memory to the required type Int. By binding memory, it can be accessed in a type-safe way. Memory binding is done behind the scenes when you create a typed pointer.

[…]

Never bind memory to two unrelated types at once. This is called Type Punning and Swift does not like puns. Instead, you can temporarily rebind memory with a method like withMemoryRebound(to:capacity:). Also, the rules say it is illegal to rebind from a trivial type (such as an Int) to a non-trivial type (such as a class). Don’t do it.

Previously: Passing an Array of Strings From Swift to C, Swift 3.0 Unsafe World, Swift and C Libraries.

Comments RSS · Twitter

Leave a Comment