Skip to content

Instantly share code, notes, and snippets.

@CentrumGuy
Last active April 15, 2020 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CentrumGuy/0fda355d7af25073d11778d61d9caf2f to your computer and use it in GitHub Desktop.
Save CentrumGuy/0fda355d7af25073d11778d61d9caf2f to your computer and use it in GitHub Desktop.
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