gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:10:07 25 4
gpt4 key购买 nike

我需要你的帮助,此代码在 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

关于swift3 - Swift 3 - 将 c 结构 sockaddr_in 转换为 CFData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39371518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com