Last active
April 15, 2020 21:55
-
-
Save CentrumGuy/0fda355d7af25073d11778d61d9caf2f to your computer and use it in GitHub Desktop.
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
import Cocoa | |
import AVFoundation | |
import CoreAudio | |
// The Weak struct is the weak wrapper | |
struct Weak<T: AnyObject> { | |
weak var object: T? | |
} | |
// TestObject represents the AudioPlayer class | |
class TestObject { | |
let value = "test" | |
init () { | |
// This is where you would set up the audio and get a working AUGraph that can generate notifications | |
var graph: AUGraph? | |
NewAUGraph(&graph) | |
// Create a wrapper for this object | |
var weakWrapper = Weak<TestObject>() | |
weakWrapper.object = self | |
// Create the wrapper pointer | |
let size = MemoryLayout<Weak<TestObject>>.size | |
let weakWrapperPointer = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: 1) | |
weakWrapperPointer.storeBytes(of: weakWrapper, as: Weak<TestObject>.self) | |
// This is the problem. I can't figure out how to get this to work without crashing | |
AUGraphAddRenderNotify(graph!, { (rawPointer, _, _, _, _, _) -> OSStatus in | |
let weakWrapperPointer = rawPointer.assumingMemoryBound(to: Weak<TestObject>.self) | |
let weakWrapper = weakWrapperPointer.pointee | |
if let object = weakWrapper.object { | |
print(object.value) | |
} | |
return noErr | |
}, weakWrapperPointer) | |
} | |
} | |
// Create a test object (represents the AudioPlayer) | |
var testObject: TestObject? = TestObject() | |
// Remove test object from memory after 3 seconds | |
DispatchQueue.main.asyncAfter(deadline: .now() + 3) { | |
testObject = nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment