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

时间:2016-09-07 13:40:20

标签: swift3 unsafe-pointers

我需要你的帮助,这段代码在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但是如何? 感谢

1 个答案:

答案 0 :(得分:4)

NSData有一个方便的方法可以帮助您解决此问题,然后您可以利用免费桥接将其投射到CFData

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