@ksemianovās code is actually incorrect. It does correctly avoid escaping the pointer from the closure and it may work in some cases, however, it is considered a programmer error in Swift to use UnsafeRawPointer.assumingMemoryBound(to:) when the memory at the pointerās location is not actually bound to that type. For more information, watch the videos I linked in my previous post.
The way I would write your code is:
import CoreStructures
struct CArrayQuestion {
func makeStencil() {
let array = Array(repeating: SIMD3<Float>.random(in: 0...1), count: Int(STENCIL3D))
// FYI the above code will not fill this array with random data. Instead, it will generate one
// random SIMD<Float> instance and repeat that instance for the rest of the array.
let cStencil = array.withUnsafeBytes {
return $0.load(as: Stencil3x3.self) // This is allowed because Stencil3x3 only has one
// stored property (a tuple of 24 SIMD3<Float>
// instances), so its layout is the same as its
// stored property.
}
}
func run() {
makeStencil()
}
}
I have added comments to the code to clarify what itās doing.
You may not even need to create an array in the first place. This version of the makeStencil() function will work the same way as it does in the above code, but it will be faster due to it requiring fewer allocations and it will be safer because it doesnāt require any unsafe code:
func makeStencil() {
let val = SIMD3<Float>.random(in: 0...1)
let cStencil = Stencil3x3(offsets: (
val, val, val, val, val, val, val, val,
val, val, val, val, val, val, val, val,
val, val, val, val, val, val, val, val))
}
I hope this helps!