In the Core Audio
-Framework user data can be passed into callbacks via an UnsafeMutableRawPointer?
. I was wondering how to pass a struct by reference via this UnsafeMutableRawPointer?
. Changes made inside the callback should be reflected outside the callback.
I set up a playground to test this:
struct TestStruct {
var prop1: UInt32
var prop2: Float64
var prop3: Bool
}
func printTestStruct(prefix: String, data: TestStruct) {
print("\(prefix): prop1: \(data.prop1), prop2: \(data.prop2), prop3: \(data.prop3)")
}
func testUnsafeMutablePointer(data: UnsafeMutableRawPointer?) {
var testStructInFunc = data!.load(as: TestStruct.self)
printTestStruct(prefix: "In func (pre change)", data: testStructInFunc)
testStructInFunc.prop1 = 24
testStructInFunc.prop2 = 1.2
testStructInFunc.prop3 = false
printTestStruct(prefix: "In func (post change)", data: testStructInFunc)
}
var testStruct: TestStruct = TestStruct(prop1: 12, prop2: 2.4, prop3: true)
printTestStruct(prefix: "Before call", data: testStruct)
testUnsafeMutablePointer(data: &testStruct)
printTestStruct(prefix: "After call", data: testStruct)
Sadly it seems like any changes to testStruct
made inside the testUnsafeMutablePointer
function are lost after the function call.
I was thinking, that the UnsafeMutableRawPointer
behaves like a pass by reference here? What am I missing out?