Boon
Boon

Reputation: 41470

How to convert from [Float] to UnsafeMutablePointer<Float> in Swift?

I have an array of Float (i.e. [Float]) and I need to call a C function from Swift that expects UnsafeMutablePointer<Float>. What's the correct way to do the conversion?

Upvotes: 2

Views: 2864

Answers (3)

MD. Rejaul Hasan
MD. Rejaul Hasan

Reputation: 176

buffer.contents().assumingMemoryBound(to: Float.self)

here buffer is your allocated memory. contents() return a pointer of this memory and assumingMemoryBound cast the type you want for that memory block.

Upvotes: 0

Sombre Osmo&#39;z
Sombre Osmo&#39;z

Reputation: 175

Swift 4/5:

if you want to copy your "Float" array into a new allocated memory use the following code:

// A float array
let floats : [Float] = [/* ... */] 

// Allocating sufficient space to store or data
let pointerToFloats = UnsafeMutablePointer<Float>.allocate(capacity: floats.count)

// Copying our data into the freshly allocated memory 
pointerToFloats.assign(from: floats, count: floats.count)

// Here you can use your pointer and pass it to any function
pointerWork(pointerToFloats)

But if you want to use the same memory of your current array use instead the following line:

let pointerToFloats = UnsafeMutablePointer<Float>.init(mutating: floats)

Here you don't have to assign your data to the memory because the pointer reference the same continuous memory of your float array

Upvotes: 6

Woof
Woof

Reputation: 1383

When I was trying to make same conversion, I used this code:

func someFunc(_ values: [Float]) {
    for value in values {
        //we need to make that value mutable. You can use inout to make parameters mutable, or use vars in "for in" statement
        var unsafeValue = value
        //then put that value to the C function using "&"
        someCFunc(value: &unsafeValue)
    }

}

I'm not sure that this is the best way, but it works for me

Upvotes: 0

Related Questions