swift - 从 swift 设置 char[] 到 c 结构中

标签 swift

C 结构体中的 char[10] 作为 10 个 UInt8 项的元组导入。有很多关于如何从该结构成员中以 swift 字符串形式读取值的示例,但我希望能够在成员中设置某些内容?

struct CStrut {
char[10] item;
}

如何快速设置 item 的值?

最佳答案

一种方法是使用withUnsafeMutablePointer(_:_:):

var a = CStruct(item: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9))
var CStructPtr = withUnsafeMutablePointer(&a.item) { (b) -> UnsafeMutableBufferPointer<Int8> in
    // UnsafeMutableBufferPointer is used because it a little more safe.
    return UnsafeMutableBufferPointer(start: UnsafeMutablePointer<Int8>(b), count: 10)
}

//Modify the tuple however you want
CStructPtr[0] = 42
CStructPtr[1] = 30

关于swift - 从 swift 设置 char[] 到 c 结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38065459/

相关文章:

ios - NSObject 和 AnyObject 有什么区别?什么时候用这两个?

ios - EXC_BAD_ACCESS 在 Swift 中访问自定义 MKAnnotation 的属性时

ios - swift 。为自定义区域设置设置特定时间格式(12/24 小时)

ios - 如何为导航栏设置自定义(RGB)颜色?

swift - 未调用索引路径中行的 UITAbleview 单元格

ios - 当我展开 UITextView 时,滚动不起作用

swift - 在 Swift 中制作结构字典时必须导入 Foundation 吗?

ios - SwiftUI 如果让内部 View

swift - NSPredicate 获取属性不在给定数组中的实体

swift - 在 Swift 中,如何获取按下按钮的单元格的行?