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

unsafemutablepointer
unsafemutablepointer<uint8
convert unsafemutablepointer to data
unsafemutablepointer<objcbool
swift convert unsafemutablepointer to array
unsafemutablepointer offset
swift unsafepointer to unsafemutablepointer
unsafemutablerawpointer

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?

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

UnsafeMutablePointer, UnsafeMutablePointer provides no automated memory management or Convert your pointer to an UnsafeMutableRawPointer instance and then use the raw� //vData is pointer to the MTLBuffer's Float data contents let pData = vertexBuffer.contents() let xPointer = pData + 256 * constantDataBufferIndex let vData = UnsafeMutablePointer<Float>(xPointer) //reset the vertices to default before adding animated offset vData.initializeFrom(vertexData)

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

How convert UnsafeMutablePointer T…, How convert UnsafeMutablePointer To UnsafeMutableRawPointer //vData is pointer to the MTLBuffer's Float data contents let pData = vertexBuffer.contents()� Implicit Casting and Bridging. When calling a function or method with an Unsafe Mutable Raw Pointer parameter, you can pass an instance of that specific pointer type, pass an instance of a compatible pointer type, or use Swift’s implicit bridging to pass a compatible pointer.

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.

UnsafeMutablePointer — SwiftDoc.org, let pointer: UnsafeMutablePointer = UnsafeMutablePointer(mutating: initalArray) @capnslipp It work because a "Float" or "Int" array is also a� Swift 3 introduces an UnsafeRawPointer type and enforces type safety with respect to unsafe pointer conversion. error: cannot invoke initializer for type 'UnsafePointer<_>' with an argument list of type '(UnsafeRawPointer)' note: Pointer conversion restricted: use '.assumingMemoryBound(to:)' or

Array -> UnsafeMutablePointer -> Array � GitHub, It replaces Unsafe[Mutable]Pointer<Void> . Conversion from Binding memory allows for safe conversion between pointer types. let floatPtr = rawPtr. let floatSize = memSize * sizeof (Float. self) let finalBuffer = unsafeBitCast (malloc (floatSize), UnsafeMutablePointer < Float >. self) // Convert the uint_8t to float. Note: a uint of 255 will convert to 255.0f. vDSP_vfltu8 (inBuffer, 1, finalBuffer, 1, UInt (memSize)) // Divide each float by 255.0 to get the 0-1 range we are looking for

UnsafeRawPointer Migration, let pointer = UnsafeMutablePointer<Int>.allocate(capacity: 1)// Initializes Calling storeBytes(of:toByteOffset:as:) does not change the bound type of 3.0]) // 1.0func takesMutablePointer(_ p: UnsafeMutablePointer<Float>) { You allocate memory using UnsafeMutablePointer.allocate. The generic parameter lets Swift know you’re using the pointer to load and store values of type Int . You must initialize typed memory before use and deinitialize it after use.

Manual Memory Management in Swift | by Shohei Yokoyama, returns 1 MemoryLayout<Bool>.stride // returns 1 MemoryLayout<Float>.size // returns 4 You allocate memory using UnsafeMutablePointer .allocate . do { print("Converting raw pointers to typed pointers") let rawPointer� Since the callback needs a void pointer, we first obtain a COpaquePointer with toOpaque() and then convert it to UnsafeMutablePointer<Void>. In the callback, we perform the same operations in reverse to obtain a reference to the original class and modify its value.

Comments
  • The exact same way I suggested in the comments of your previous question ;)
  • @Hamish Can you list that as an answer below and I will select it?
  • I went with the last line and for some bizarre reason I had to remove the ".init" in Swift 4.2 and just use: let pointerToFloats = UnsafeMutablePointer<Float>(mutating: floats)
  • I agree it's bizarre but it does the same so ... :)
  • Did you mean to pass unsafeValue to the someCFunc function instead of value? And how is this passing the array to a C function? This is passing a single Float.
  • @rmaddy in the question, his C function requires single value, not an array. And I don't remember that C can receive arrays as parameters from swift. It can be only tuples
  • The function expects a pointer to a float, not a float. In C, a pointer to a float as function arg is equivalent to an array since you are pointing to the beginning of the array.
  • @Boon are you sure that your C function requires an array of floats as unsafepointer? I know that add &I make value as unsafe pointer, but it works only for a single value. When C func requires an array, then the swift code converts it to tuple. Could you show the original C function in your question?
  • @Woof The C function is from an SDK, I don't have access to it. Yes it's unsafe pointer - that's what the compiler indicates it is looking for.