在 Swift 中使用 C 风格的无符号字符数组和按位运算符 [英] Using C style unsigned char array and bitwise operators in Swift

查看:62
本文介绍了在 Swift 中使用 C 风格的无符号字符数组和按位运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将一些 Objective-C 代码更改为 Swift,但我终生无法弄清楚如何在此特定代码实例中处理无符号字符数组和按位运算.

I'm working on changing some Objective-C Code over to Swift, and I cannot figure out for the life of me how to take care of unsigned char arrays and bitwise operations in this specific instance of code.

具体来说,我正在将以下 Objective-C 代码(处理 CoreBluetooth)转换为 Swift:

Specifically, I'm working on converting the following Objective-C code (which deals with CoreBluetooth) to 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 中尝试了以下操作:

I've tried the following in Swift:

var advertisementBytes: CMutablePointer<CUnsignedChar>
self.proximityUUID.getUUIDBytes(advertisementBytes)
advertisementBytes[16] = (CUnsignedChar)(self.major >> 8)

我遇到的问题是 Swift 中的 getUUIDBytes 似乎只将 CMutablePointer<CUnsignedChar> 对象作为参数,而不是 CUnsignedChars 的数组,所以我不知道如何对 adsBytes 执行后面的按位运算,因为它似乎需要一个 unsignedChar 数组才能这样做.

The problems I'm running into are that getUUIDBytes in Swift seems to only take a CMutablePointer<CUnsignedChar> object as an argument, rather than an array of CUnsignedChars, so I have no idea how to do the later bitwise operations on advertisementBytes, as it seems it would need to be an unsignedChar array to do so.

此外,CMutablePointer 会抛出一个错误,指出 Swift 中的 CMutablePointers 不支持固定长度数组.

Additionally, CMutablePointer<CUnsignedChar[21]> throws an error saying that fixed length arrays are not supported in CMutablePointers in Swift.

有人可以就潜在的变通方法或解决方案提出建议吗?非常感谢.

Could anyone please advise on potential work-arounds or solutions? Many thanks.

推荐答案

查看 与 C API 交互

主要是这个

C 可变指针

当一个函数被声明为采用 CMutablePointer 时参数,它可以接受以下任何一项:

When a function is declared as taking a CMutablePointer argument, it can accept any of the following:

  • nil,作为空指针传递
  • CMutablePointer 值
  • 一个输入输出表达式,其操作数是类型类型的存储左值,作为左值的地址传递
  • 一个输入输出 Type[] 值,它作为指向数组开头的指针传递,并且在通话期间延长生命周期

如果你声明了一个像这样的功能:

If you have declared a function like this one:

快速

func takesAMutablePointer(x: CMutablePointer<Float>) { /*...*/ } You

可以通过以下任何一种方式调用它:

can call it in any of the following ways:

快速

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)

这篇关于在 Swift 中使用 C 风格的无符号字符数组和按位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆