代码之家  ›  专栏  ›  技术社区  ›  blkpingu aaquib

无法将类型“Int”的值转换为预期的参数类型“UnsafeRawPointer”

  •  0
  • blkpingu aaquib  · 技术社区  · 4 年前

    我想做的事

    初始化包含 Int 价值

    问题

    import MetalKit
    
    ...
    
    func doStuff(gra: [Int], dist: Int) {
        let graphBuff = device?.makeBuffer(bytes: gra,
                                          length: MemoryLayout<Int>.size * count,
                                          options: .storageModeShared)
        let distanceBuff = device?.makeBuffer(bytes: dist, // Cannot convert value of type 'Int' to expected argument type 'UnsafeRawPointer'
                                          length: MemoryLayout<Int>.size,
                                          options: .storageModeShared)
    }
    

    由于某些原因,它不允许初始化类型为的缓冲区 整数 但是 [Int] 我有点不知所措发生了什么事。

    1 回复  |  直到 4 年前
        1
  •  1
  •   Spo1ler    4 年前

    原因是Swift有一些编译器魔法,可以将数组传递给不安全的指针。这种魔力不仅仅局限于常规类型。

    func withUnsafeBytes(of: &T, body: (UnsafeRawBufferPointer) throws -> Result(UnsafeRawBufferPointer) throws -> Result) -> Result

    例如:

      3> var someInt: Int = 3
    someInt: Int = 3
      4> withUnsafeBytes(of: &someInt) { print($0) }
    UnsafeRawBufferPointer(start: 0x00000001000ec4d0, count: 8)
    

    但是你可以用

    let buffer = device?.makeBuffer(length: MemoryLayout<Int>.size,
                       options: .storageModeShared)!
    

    然后使用 contents() 指针:

    buffer.contents().storeBytes(of: dist, as: Int.self)