Using an unsigned C-style char array and bitwise operators in Swift

I am working on changing Objective-C code to Swift, and I cannot figure out how much I should care about unsigned char arrays and bitwise operations in this particular code instance.

In particular, I am 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); 

I tried the following in Swift:

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

The problems I'm encountering is that getUUIDBytes in Swift apparently only accepts a CMutablePointer<CUnsignedChar> object as an argument, not a CUnsignedChars array, so I have no idea how to perform later bitwise operations on advertBytes, like it seems there must be an unsignedChar array for this.

In addition, CMutablePointer<CUnsignedChar[21]> displays a message stating that fixed-length arrays are not supported in CMutablePointers in Swift.

Can anyone consult with potential problems or solutions? Many thanks.

+8
objective-c swift
source share
1 answer

See Interacting with the API API

Mainly

C Mutable Pointers

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

  • nil, which is passed as a null pointer
  • CMutablePointer value
  • An input expression whose operand is a stored value l of type Type, which is passed as the address lvalue
  • The value of in-out Type [], which is passed as a pointer to the beginning of the array, and extending the lifespan for the duration of the call

If you declared a function like this:

SWIFT

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

can call it in one 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) 

So the code becomes

 var advertisementBytes = CUnsignedChar[]() self.proximityUUID.getUUIDBytes(&advertisementBytes) advertisementBytes[16] = CUnsignedChar(self.major >> 8) 
+7
source share

All Articles