What I'm trying to do
Initialise a buffer for metal that contains an Int
value
The Problem
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)
}
for some reason it does not allow to init a buffer with type Int
, but [Int]
is fine.
I'm kind of at a loss here what's going on.
CodePudding user response:
The reason for this is Swift has some compiler magic for passing arrays to unsafe pointers. This magic doesn't extend to just regular types.
You can kinda do similar thing to the magic compiler is doing yourself using this freestanding function from standard library func withUnsafeBytes(of: &T, body: (UnsafeRawBufferPointer) throws -> Result(UnsafeRawBufferPointer) throws -> Result) -> Result
For example:
3> var someInt: Int = 3
someInt: Int = 3
4> withUnsafeBytes(of: &someInt) { print($0) }
UnsafeRawBufferPointer(start: 0x00000001000ec4d0, count: 8)
But instead you can just make a regular buffer with
let buffer = device?.makeBuffer(length: MemoryLayout<Int>.size,
options: .storageModeShared)!
and then put anything you want in it using contents()
pointer:
buffer.contents().storeBytes(of: dist, as: Int.self)