Swift 3 - 将 c 结构 sockaddr_in 转换为 CFData

Swift 3 - Convert c structure sockaddr_in to CFData

我需要你的帮助,此代码在 Swift 3

中不再编译
//: Let's set up the `sockaddr_in` C structure using the initializer.
var sin = sockaddr_in(
    sin_len: UInt8(sizeof(sockaddr_in)),
    sin_family: sa_family_t(AF_INET),
    sin_port: in_port_t(0),
    sin_addr: in_addr(s_addr: inet_addr(routerIP)),
    sin_zero: (0,0,0,0,0,0,0,0)
)

//: Now convert the structure into a `CFData` object.
let data = withUnsafePointer(&sin) { ptr in
    CFDataCreate(kCFAllocatorDefault, UnsafePointer(ptr), sizeof(sockaddr_in))
}

//: Create the `CFHostRef` with the `CFData` object and store the retained value for later use.
host = CFHostCreateWithAddress(kCFAllocatorDefault, data).takeRetainedValue()

我必须修复线路 "withUnsafePointer" 但我不知道如何?

我试过这样的东西

    let data = withUnsafePointer(to: &sin) { ptr in
        CFDataCreate(kCFAllocatorDefault, UnsafePointer(ptr), MemoryLayout<sockaddr_in>.size)
    }

编译器说我必须使用 withMemoryRebound 但如何使用? 谢谢

NSData 有一个方便的方法来帮助您,然后您可以利用免费桥接将其转换为 CFData:

let data = NSData(bytes: &sin, length: MemoryLayout<sockaddr_in>.size) as CFData