Created
July 21, 2021 19:25
-
-
Save EricRabil/597c062c21adb5158c2a3792a4d7357e to your computer and use it in GitHub Desktop.
withUnsafeMutablePointer for safe allocation interoperability
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| 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