简体   繁体   中英

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

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM