gpt4 book ai didi

Swift “UDP Read” 代码 - unsaferawbufferpointer 编译错误

转载 作者:行者123 更新时间:2023-11-28 07:33:00 25 4
gpt4 key购买 nike

我相信有人可以在几秒钟内解决这个问题,但我对 swift 还很陌生,在 iPad 上使用 playgrounds。我正在尝试修改一些 SendUDP 代码以改为接收,但我无法解决 readResult= 行上的编译错误(unsafepointer is not convertible to unsaferawbufferpointer)。 SEND 使用非常相似的代码工作正常,但我真的在这里挣扎,超出了我的理解范围......

代码如下

func readUDP() {
guard
let addresses =
try ? addressesFor(host: "192.168.4.1", port: 80)
else {
print("host not found")
return
}
if addresses.count != 1 {
print("host ambiguous; using the first one")
}
address = addresses[0]
fd1 = socket(Int32(address.ss_family), SOCK_DGRAM, 0)
guard fd1 >= 0
else {
print("`socket` failed`")
return
}
defer {
let junk = close(fd1)
assert(junk == 0)
}

var message = [UInt8](repeating: 0, count: 1024)
let messageCount = message.count
var readResult = message.withUnsafeBytes {
(messagePtr: UnsafePointer < UInt8 > ) - > Int in
return address.withSockAddr {
(sa, saLen) - > Int in
return recvfrom(fd1, messagePtr, messageCount, 0, sa, & saLen)
}
}
guard readResult >= 0
else {
print("read failed")
return
}
print("success")
}

最佳答案

您可以使用 Swift 的 implicit bridging简化成这样:

var message = [UInt8](repeating: 0, count: 1024)
let messageCount = message.count
var readResult = address.withSockAddr {
(sa, saLen) - > Int in
return recvfrom(fd1, &message, messageCount, 0, sa, &saLen)
}
guard readResult >= 0
else {
print("read failed")
return
}

关于Swift “UDP Read” 代码 - unsaferawbufferpointer 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54139405/

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