Swift 3-通过UnsafemtableRawPointer通过引用传递结构?

Swift 3-通过UnsafemtableRawPointer通过引用传递结构?,swift,swift3,pass-by-reference,core-audio,unsafemutablepointer,Swift,Swift3,Pass By Reference,Core Audio,Unsafemutablepointer,在核心音频中-框架中,用户数据可以通过非FemeutableRawPointer?传递到回调中。我想知道如何通过这个unsafemtablerawpointer?通过引用传递结构。在回调内部所做的更改应该反映在回调外部 我建立了一个游乐场来测试这一点: struct TestStruct { var prop1: UInt32 var prop2: Float64 var prop3: Bool } func printTestStruct(prefix: String

核心音频中
-框架中,用户数据可以通过
非FemeutableRawPointer?
传递到回调中。我想知道如何通过这个
unsafemtablerawpointer?
通过引用传递结构。在回调内部所做的更改应该反映在回调外部

我建立了一个游乐场来测试这一点:

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)
不幸的是,在函数调用之后,
testUnsafeMutablePointer
函数内部对
testStruct
所做的任何更改似乎都会丢失


我在想,
unsafemeutablerawpointer
在这里的行为就像一个pass-by-reference?我遗漏了什么?

您的函数将数据复制到本地结构中,但没有 将修改后的数据复制回来。因此,这将是一个可能的解决方案 特殊情况下的解决方案:

func testUnsafeMutablePointer(data: UnsafeMutableRawPointer?) {
    var testStructInFunc = data!.load(as: TestStruct.self)

    testStructInFunc.prop1 = 24
    testStructInFunc.prop2 = 1.2
    testStructInFunc.prop3 = false

    data!.storeBytes(of: testStructInFunc, as: TestStruct.self)
}
但是请注意,只有当结构只包含“simple”时,这才有效 值类似于整数和浮点值。“复杂”类型 like数组或字符串包含指向实际存储的不透明指针 不能像这样简单地复制

另一个选项是修改指向结构,如下所示:

func testUnsafeMutablePointer(data: UnsafeMutableRawPointer?) {
    let testStructPtr = data!.assumingMemoryBound(to: TestStruct.self)

    testStructPtr.pointee.prop1 = 24
    testStructPtr.pointee.prop2 = 1.2
    testStructPtr.pointee.prop3 = false
}
这两种解决方案都假设回调时结构仍然存在 调用,因为传递指针并不能确保 指向的结构的生存期

作为替代,考虑使用<代码>类< /代码>的实例。 将保留的或未保留的指针传递到实例允许控制 回调处于“活动”状态时对象的生存期,比较


.

非常感谢!这对我来说绝对是件好事。这里最快捷的解决方案是什么(我假设使用
class
,但我对Swift很陌生)?@Herickson:如果没有更多的上下文,很难判断。您正在与C API交互,因此没有纯Swift。