5

In Swift I want to pass a data buffer (named data) of type Data to a C function (named do_something) that takes a pointer of type UnsafePointer<UInt8>.

Is the code example below correct? And if so, in this case is it OK to use assumingMemoryBound(to:) instead of bindMemory(to:capacity:)?

data.withUnsafeBytes { (unsafeBytes) in
  let bytes = unsafeBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)
  do_something(bytes, unsafeBytes.count)
}
0

1 Answer 1

4

The correct way is to use bindMemory():

data.withUnsafeBytes { (unsafeBytes) in
    let bytes = unsafeBytes.bindMemory(to: UInt8.self).baseAddress!
    do_something(bytes, unsafeBytes.count)
}

assumingMemoryBound() must only be used if the memory is already bound to the specified type.

Some resources about this topic:

9
  • If I'm not mistaken isn't it easier to convert Data to [UInt8] and pass this as a pointer?
    – vadian
    Aug 24, 2020 at 19:36
  • 3
    @vadian: Easier to code but less efficient at runtime. It would create an additional (temporary) array.
    – Martin R
    Aug 24, 2020 at 19:37
  • Thank you, but how do you know the memory hasn't already been bound to the UInt8 type?
    – ma11hew28
    Aug 25, 2020 at 3:31
  • @ma11hew28: bindMemory binds or rebinds the memory location, so it does not matter if it is already bound to UInt8. There is also good information here: stackoverflow.com/a/47942269/1187415. Note also that “Binding memory communicates to the compiler that the memory locations are safe for typed access. Nothing happens at runtime--until someone writes a type safety sanitizer.”
    – Martin R
    Aug 25, 2020 at 16:52
  • OK. But I want my app to run fast. Are you saying that even if I (unnecessarily) rebind memory to a type that it's already bound to, then my app will run just as fast (as if I hadn't)?
    – ma11hew28
    Aug 25, 2020 at 18:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.