UnsafePointer initializer in Swift 3

前端 未结 3 466
挽巷
挽巷 2021-02-05 04:09

I have a receipt validation class that is deprecated since Swift 3 has released. I fixed some issues, but I still have many ...

Here is the GitHub source code I used : h

相关标签:
3条回答
  • 2021-02-05 04:49

    It is possible to put a regular pointer sign i C & in front of a Int8 array or Uint8 array to make a pointer to supply a C-function input. Like the &aBuffer array below (but the data array must copied locally first, to keep control of the storage of the data storage until finished with the operation, you get an error else). Here in a routine handling dropInteraction data (delivering a byte array):

    func interpretInstanceData(filename: String, Buffer: [UInt8]) -> String {
        var aBuffer = Buffer
        let sInstanceData = String(cString: Ios_C_InterpretInstanceData(filename, &aBuffer, Int32(aBuffer.count)))
    

    The question is slightly old. But googling for a solution on the topic of converting a swift byte array to a C-pointer (what else is UnsafePointer< UInt8 >). This question made a hit. But I think this answer is helpful for later editions of Swift (that I use). Would have worked even then. Worked in any kind of use needing a pointer from swift (just make the array of right type first).

    0 讨论(0)
  • 2021-02-05 04:52

    May have recently changed to just this, without the ".bytes." part:

    var p: UnsafePointer = data.assumingMemoryBound(to: UInt8.self)
    

    from the original:

    var p = UnsafePointer<UInt8>(data.bytes)
    
    0 讨论(0)
  • 2021-02-05 05:01
    1. In Swift 3, you cannot init an UnsafePointer using an UnsafeRawPointer.

      You can use assumingMemoryBound(to:) to convert an UnsafeRawPointer into an UnsafePointer<T>. Like this:

      var ptr = data.bytes.assumingMemoryBound(to: UInt8.self)
      
    2. Use debugDescription or distance(to:) to compare two pointer.

      while(ptr.debugDescription < endPtr.debugDescription)
      

      or

      while(ptr.distance(to:endPtr) > 0)
      
    0 讨论(0)
提交回复
热议问题