Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save EricRabil/597c062c21adb5158c2a3792a4d7357e to your computer and use it in GitHub Desktop.

Select an option

Save EricRabil/597c062c21adb5158c2a3792a4d7357e to your computer and use it in GitHub Desktop.
withUnsafeMutablePointer for safe allocation interoperability
/**
Helper function for efficiently initializing a value based on a pointer
- Parameter type: the type of value the pointers value will be cast to
- Parameter closure: block of code that will handle the pointer
- Returns: tuple of (value the pointer was given, return type of closure)
*/
func withUnsafeMutablePointer<T, R>(ofType type: T.Type, _ closure: (UnsafeMutablePointer<T>) -> R) -> (T?, R) {
let ptr = UnsafeMutablePointer<T>.allocate(capacity: 1)
defer {
// close out the pointer once this is done
ptr.deallocate()
}
// pass pointer to closure
let ret = closure(ptr)
return (ptr.move(), ret)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment