UnsafePointer<Int8> 不工作

UnsafePointer<Int8> not working

以下单元测试总是失败,因为一些 UnsafePointer 等于其他一些。我观察到至少 3 个字符串的这种行为。 我在 High Sierra 版本 10.13.1 (17B48) 上使用 Xcode 版本 9.1 (9B55)。

func testUnsafePointer() {
    let a = "aaa"
    let b = "bbb"
    let c = "ccc"

    let ua = UnsafePointer<Int8>(a)
    let ub = UnsafePointer<Int8>(b)
    let uc = UnsafePointer<Int8>(c)

    print("a: '\(a)', ua: '\(ua)'")
    print("b: '\(b)', ub: '\(ub)'")
    print("c: '\(c)', uc: '\(uc)'")

    XCTAssertTrue(ua != ub)
    XCTAssertTrue(ub != uc)
    XCTAssertTrue(uc != ua)
}

打印输出类似于此

a: 'aaa', ua: '0x000060c000056a30'
b: 'bbb', ub: '0x00006080000530d0'
c: 'ccc', uc: '0x00006080000530d0'

注意。在 swift 操场上,一切看起来都很好。

let ua = UnsafePointer<Int8>(a)

init(_ other: UnsafePointer<Pointee>)

UnsafePointer 的初始化器被调用。 IE。你路过 a Swift String 到采用 UnsafePointer<Int8> 的函数 争论。在那种情况下,一个 temporary C 字符串表示被创建并传递给函数, 比较 String value to UnsafePointer<UInt8> function parameter behavior.

该临时 C 字符串仅在函数运行期间有效 调用,在return上,不保证内存指向 to by ua 仍然包含该 C 字符串(或任何有效数据)。此外,

let ua = UnsafePointer<Int8>(a)
let ub = UnsafePointer<Int8>(b)
let uc = UnsafePointer<Int8>(c)

可以为临时 C 字符串使用相同的存储空间,在这种情况下 如您所见,指针将相等。


如果您打算调用带有 const char * 个参数的 C 函数,那么您只需传递 Swift 个字符串即可。编译器 将插入必要的代码来创建 C 字符串表示 (在函数调用期间再次有效), 如 String value to UnsafePointer<UInt8> function parameter behavior 中所述:

let a = "aaa"
let b = "bbb"
let c = "ccc"

cfunc(a, b, c)