swift无法将类型'in_addr_t'(又名'UInt32')的值转换为预期的参数类型'UnsafeMutablePointer <in_addr_t>!'

时间:2017-07-18 05:24:11

标签: swift unsafe-pointers

我尝试将目标c中的函数添加到swift中,就像这里https://stackoverflow.com/a/29440193/7395969一样,我将调用方法转换为Swift,如下所示。但是我收到错误:无法在此行上将'in_addr_t'类型的值(也称为'UInt32')转换为预期的参数类型'UnsafeMutablePointer!' let r:Int < / p>

func getGatewayIP() -> String {
    var ipString: String? = nil

    let gatewayaddr: in_addr
    let r: Int = getdefaultgateway((gatewayaddr.s_addr))
    if r >= 0 {
        ipString = "\(inet_ntoa(gatewayaddr))"
        print("default gateway : \(ipString)")
    }
    else {
        print("getdefaultgateway() failed")
    }
    return ipString!
}

1 个答案:

答案 0 :(得分:1)

您必须将gatewayaddr.s_addr地址作为inout参数传递 与&。此外,gatewayaddr必须初始化:

var gatewayaddr = in_addr()
let r = getdefaultgateway(&gatewayaddr.s_addr)

请注意字符串插值

    ipString = "\(inet_ntoa(gatewayaddr))"

无法将C字符串转换为Swift String, 你必须致电String(cString:)。还

return ipString!
如果无法确定网关,

将崩溃。

安全版本的示例:

func getGatewayIP() -> String? {
    var gatewayaddr = in_addr()
    let r = getdefaultgateway(&gatewayaddr.s_addr)
    if r >= 0 {
        return String(cString: inet_ntoa(gatewayaddr))
    } else {
        return nil
    }
}

if let gateway = getGatewayIP() {
    print("default gateway", gateway)
} else {
    print("getGatewayIP() failed")
}