Objective-C/Swift usage in AudioUnit Render callback

Apple documentation advices against use of Objective-C and Swift in AudioUnit input or render callbacks. So the callbacks are written mostly in C where we can quickly copy data and pass that data to secondary thread for processing. To share variables between C and Objective C/Swift, the advice is to use inRefCon as a pointer to Controller object and then access it's variable. While it is easy in Objective C to simply use the following code in AudioUnit render callback function,


MyController *controller = (MyController *)inRefCon

if (controller->muteAudio) {

...

...

}


And this guaranteed that access to muteAudio is simply access to memory address (base address of controller + offset for muteAudio var) unlike full Objective C messaging. But I can't find an equivalent in Swift as Swift has no member variables, all vars are like properties. So I am not sure if the following is the right thing to do in Swift render callback :


let controller = unsafeBitCast(inRefCon, to: MyController.self) /


if !controller.muteAudio {

...

...

}


Doesn't controller.muteAudio trigger message passing in Swift rather than simple access to memory address (base address of controller + offset for muteAudio var)?

Replies

You can pass a C struct or C array (rather than a Swift object) thru inRefCon using Swift, and use that to pass data to the audio context. Swift seems to be able to safely access C structs and arrays (read and write) if they are declared in the bridging header.