Skip to content

Instantly share code, notes, and snippets.

@kastiglione
Last active August 19, 2020 20:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kastiglione/6e1531ebf5a61e47d8b8c98ed7642e59 to your computer and use it in GitHub Desktop.
Save kastiglione/6e1531ebf5a61e47d8b8c98ed7642e59 to your computer and use it in GitHub Desktop.
// Given an imported C function, that uses a context pointer and a C callback function:
//
// func for_each(_ x: X, context: UnsafeMutableRawPointer!, callback: @convention(c) (UnsafeMutableRawPointer?, Element) -> Void)
//
// When is it safe to use this pattern?
// Example with two captured variables.
typealias Context = (Type1, Type2)
var context = (capture1, capture2)
for_each(x, context: &context) { context, element in
let (capture1, capture2) = context!.assumingMemoryBound(to: Context.self).pointee
// Perform operations with captures and `element`…
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment