Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot convert value of type 'Int' to expected argument type 'UnsafeRawPointer'

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading