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/