我正在努力将一些 Objective-C 代码更改为 Swift,但我终究无法弄清楚如何处理这个特定代码实例中的无符号字符数组和按位运算。
具体来说,我正在将以下 Objective-C 代码(处理 CoreBluetooth)转换为 Swift:
unsigned char advertisementBytes[21] = {0};
[self.proximityUUID getUUIDBytes:(unsigned char *)&advertisementBytes];
advertisementBytes[16] = (unsigned char)(self.major >> 8);
advertisementBytes[17] = (unsigned char)(self.major & 255);
我在 Swift 中尝试了以下方法:
var advertisementBytes: CMutablePointer<CUnsignedChar>
self.proximityUUID.getUUIDBytes(advertisementBytes)
advertisementBytes[16] = (CUnsignedChar)(self.major >> 8)
我遇到的问题是 Swift 中的 getUUIDBytes 似乎只需要 CMutablePointer<CUnsignedChar>
对象作为参数,而不是 CUnsignedChars 数组,所以我不知道如何对 advertisementBytes 进行后面的按位运算,因为它似乎需要一个 unsignedChar 数组才能这样做。
此外,CMutablePointer<CUnsignedChar[21]>
抛出一个错误,指出 Swift 中的 CMutablePointers 不支持固定长度数组。
任何人都可以就潜在的解决方法或解决方案提出建议吗?非常感谢。
最佳答案
主要是这个
C Mutable Pointers
When a function is declared as taking a CMutablePointer argument, it can accept any of the following:
- nil, which is passed as a null pointer
- A CMutablePointer value
- An in-out expression whose operand is a stored lvalue of type Type, which is passed as the address of the lvalue
- An in-out Type[] value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call
If you have declared a function like this one:
SWIFT
func takesAMutablePointer(x: CMutablePointer<Float>) { /*...*/ } You
can call it in any of the following ways:
SWIFT
var x: Float = 0.0 var p: CMutablePointer<Float> = nil var a: Float[] = [1.0, 2.0, 3.0] takesAMutablePointer(nil) takesAMutablePointer(p) takesAMutablePointer(&x) takesAMutablePointer(&a)
所以你的代码变成了
var advertisementBytes = CUnsignedChar[]()
self.proximityUUID.getUUIDBytes(&advertisementBytes)
advertisementBytes[16] = CUnsignedChar(self.major >> 8)
关于objective-c - 在 Swift 中使用 C 风格的无符号字符数组和按位运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24049411/