swift - 在 Swift 中为引用的 C 结构中的属性设置值

标签 swift

我想做的是修改我引用的 C 结构的值,如下所示:

在 BridgingHeader.h 中:

struct info_type {
    int priority;
};

在 ViewController.swift 中:

class MyClass {
    func viewDidLoad() {
        var info = info_type()
        info.priority = 2    
        processInfo(&info)
    }

    func processInfo(infoRef: UnsafePointer<info_type>) {
        info.memory.priority = 1
    }
}

但是,代码在 Xcode 中触发“命令因信号失败:Abort trap: 6”。打开我看到的构建输出

Assertion failed: (GetSetInfo.getInt().hasValue()), function getSetterAccessibility, file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-700.0.42.3/src/swift/include/swift/AST/Decl.h, line 4070.
0  swift                    0x0000000106d17b9b llvm::sys::PrintStackTrace(__sFILE*) + 43
1  swift                    0x0000000106d182db SignalHandler(int) + 379
2  libsystem_platform.dylib 0x00007fff8eaacf1a _sigtramp + 26
3  libsystem_platform.dylib 0x00007fff5aee4bec _sigtramp + 3426974956
4  libsystem_c.dylib        0x00007fff8ef73b53 abort + 129
[...]

我是做错了什么还是我偶然发现了 Xcode bug?我正在使用 Xcode 7.0 beta 2(版本 7.0 beta (7A121l))

最佳答案

由于 processInfo() 方法修改了指向的内存 根据 infoRef,参数必须声明为可变指针:

func processInfo(infoRef: UnsafeMutablePointer<info_type>) {
    infoRef.memory.priority = 1
}

这将按预期编译并工作。

Xcode 6.4 为您的代码发出正确的错误消息:

func processInfo(infoRef: UnsafePointer<info_type>) {
    infoRef.memory.priority = 1 // error: cannot assign to the result of this expression
}

但是 Xcode 7 beta 2 崩溃了,这是一个错误。

关于swift - 在 Swift 中为引用的 C 结构中的属性设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31249496/

相关文章:

ios - 点击单元格时 UILabel 向右移动

ios - 如何在swift中使用视觉框架从其特征点提取外唇

ios - 使用 EventKit 在 Swift 中检查并(可能)从日历中删除事件

ios - UIBezierPath 只有半个笔画

ios - 如何使用 getData() 在 Swift 中使用 ObjC PNChart 库绘制折线图?

ios - 如何从此结构访问成功/失败案例?

ios - 将 AVAsset 上传到 Firebase 存储

ios - ScrollView 中的 UIButton 没有响应

ios - AFNetworking 3.0 在应用移至后台时继续上传

json - 转换 JSON 对象以从中提取数据时出错