1 Reply
      Latest reply: Jan 26, 2017 3:46 AM by eskimo RSS
      JohnMcM Level 1 Level 1 (0 points)

        I was trying this code from https://github.com/dfrencham/swiftPCap



          pcap_loop(pcapSession, numberOfPackets,

                    (args: UnsafeMutablePointer<u_char>,
                     packet: UnsafePointer<u_char>) ->Void in
                            // lets handle the result using a call to a singleton
                            // we can keep state this way, and not have to
                            // tool around by passing pointers to UnsafePointers
                            // and dereferencing later
                            let pa = PacketAnalyser.sharedInstance

        Now it is Swift 3, I cannot compile with the following errors cannot convert value of type '(UnsafeMutablePointer, UnsafePointer, UnsafePointer) -> Void' to expected argument type 'pcap_handler!'



        Not really sure how to proceed, pretty much a newbie at referencing C code from Swift. I have read the documentation, but not having much luck.




        • Re: calling pcap_loop from Swift 3
          eskimo Apple Staff Apple Staff (6,470 points)

          In situations like this it’s best to leave off the closure types and then let Xcode help you figure things out.  For example, this code compiles:

          let p = … create this with pcap_create …
          let status = pcap_loop(p, 0, { (user, packetHeader, packetData) in
              print(user as Any)
              print(packetHeader as Any)
              print(packetData as Any)
          }, nil)

          You can then option click on user, packetHeader, and packetData to work out the types that were inferred.

          ps If you want to do anything useful inside your callback, you’ll probably want to use the user pointer (passing everything off to a singleton is less than ideal).  For an example of how to put a Swift object reference into this user pointer and how to get it back out again, you can look at this post.

          Share and Enjoy

          Quinn “The Eskimo!”
          Apple Developer Relations, Developer Technical Support, Core OS/Hardware
          let myEmail = "eskimo" + "1" + "@apple.com"