Swift中指针

想用swift写一个socket,不想混编,踩过很多坑,以做纪录。swift中的指针不像oc中那样简单,有特殊的写法。

String

var str:String = "123"

let strP =  withUnsafePointer(to: &str) { return $0
 }
strP
print(strP)
func withUnsafePointer(to value: inout T, _ body: (UnsafePointer) throws -> Result) rethrows -> Result


根据方法介绍,运用了泛类转换类型

类型转换地址转换


  func test1() {
        let address: String = "192.168.1.103"
        var port: Int32 = 16000
        var fd: Int32 = socket(AF_INET, SOCK_STREAM, 0)
        var serv_addr = sockaddr_in()
        serv_addr.sin_family = sa_family_t(AF_INET)
        serv_addr.sin_addr.s_addr = inet_addr(address)
        serv_addr.sin_port = in_port_t(port)
        let servaddr =  withUnsafePointer(to: &serv_addr) {
            return $0.withMemoryRebound(to: sockaddr.self, capacity: 1, {
                return $0
            })
        }
        
        
        let r = bind(fd, servaddr, socklen_t(MemoryLayout.size))
        if r != 0 {
            print("绑定socket失败")
        }
        
        
    }

你可能感兴趣的:(Swift中指针)