I create a connect IOS c s7-300 controller. There is a connection but I can not correctly transfer the value of type Float , I have a question with UnsafeMutableRawPointer ! how to write a float value there.

Code: Cli_DBWrite(Client:S7Object,DBNumber:Int32,Size:Int32,pUsrData:*UnsafeMutableRawPointer)

Cli_DBWrite(Client,1000,4,4,????) how to write the Float value here please tell UnsafeMutableRawPointer

  • and int not satisfied? - Max Mikheyenko
  • no have been. It is necessary to record the value in UnsafeMutableRawPointer - Marat Gafarov
  • in the sense of int, convert to UnsafeMutableRawPointer instead of float - Max Mikheyenko
  • And how can I do this code? - Marat Gafarov
  • UnsafeMutableRawPointer(bitPattern: myInt)! - Max Mikheyenko

2 answers 2

In UnsafeMutableRawPointer , the Float value can be written this way in Swift version 4.

 func __test_so_578002() { print("[TEST]: \(#function)") let x0 = Float(123456.7890) let ptr = UnsafeMutableRawPointer.allocate(bytes: MemoryLayout<Float>.stride, alignedTo: 1) ptr.storeBytes(of: x0, as: Float.self) // Используйте ptr по назначению... let x1 = ptr.load(as: Float.self) print((x0, x1)) print("[/TEST]") } 

At the exit check:

 [TEST]: __test_so_578002() (123456.789, 123456.789) [/TEST] 

    Not tested in Swift 4, but there is a fairly compact version in Swift 3

     var testVar:Float = 15.0 let testPointer = UnsafeMutableRawPointer(&testVar) let newValue = testPointer.load(as: Float.self) // newValue = testVar 

    You need to pass to the testPointer method

    But Apple, here , writes that it can be even easier. Let you have a certain method accepting UnsafeMutablePointer<Float>

     func takesAMutablePointer(_ p: UnsafeMutablePointer<Float>) { // ... } var x: Float = 0.0 var a: [Float] = [1.0, 2.0, 3.0] takesAMutablePointer(&x) takesAMutablePointer(&a) 

    so in your case just

     var yourFloatValue: = 3.141592 Cli_DBWrite(Client, 1000, 4, 4, &yourFloatValue)