Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting an [Float] to [simd_float4] in Swift

Tags:

c

swift

simd

I have this c function that I call from Swift but I think it should be possible to implement in Swift, the trick is to be able to cast the memory for the array of floats to an array of simd_float4. Below is my c function and how I call it in Swift

swift

sumFloats(&y, y1, n, anAmplitudes[z]);

C

void sumFloats(float * y, const float * x, const int yc, const float a) {
    simd_float4 theA = simd_make_float4(a,a,a,a);
    simd_float4 * theY = (simd_float4*)y;
    simd_float4 * theX = (simd_float4*)x;
    assert( (yc&0x3) == 0 );
    for( int t = 0, theYC = yc >> 2; t < theYC; t ++ ) {
        theY[t] += theA * theX[t];
    }
}

also my understanding is an Array doesn't guarantee a continuous block of memory so there must some conversion going on when calling the C code, I can probable fix that by using a ContiguousArray, but I can't use a ContiguousArray to call C.

like image 672
Nathan Day Avatar asked Dec 17 '25 19:12

Nathan Day


1 Answers

withUnsafe(Mutable)BufferPointer() can be used to get a pointer to the array's (mutable) storage, and withMemoryRebound() to access the array of Float as an array of float4:

func sumFloats(y: inout [Float], x: [Float], yc: Int, a: Float) {
    let theA = simd_float4(a, a, a, a)
    x.withUnsafeBufferPointer {
        $0.baseAddress!.withMemoryRebound(to: simd_float4.self, capacity: yc / 4) { theX in
            y.withUnsafeMutableBufferPointer {
                $0.baseAddress!.withMemoryRebound(to: simd_float4.self, capacity: yc / 4) { theY in
                    for t in 0..<yc/4 {
                        theY[t] = theA * theX[t]
                    }
                }
            }
        }
    }
}

Example:

let x: [Float] = [1, 2, 3, 4, 5, 6, 7, 8]
var y: [Float] = [0, 0, 0, 0, 0, 0, 0, 0]

sumFloats(y: &y, x: x, yc: 8, a: 2.0)
print(y) // [2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0]
like image 50
Martin R Avatar answered Dec 19 '25 12:12

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!