JAL JAL - 3 months ago 23
Swift Question

Behavior of getCString and withCString on different architectures

I'm trying to implement AES 128 in Swift and recently ran into a problem with writing a Swift String to a

CChar
array:

let testString = "myTestString"

var keyPtr = [CChar](count: kCCKeySizeAES128 + 1, repeatedValue: 0)
bzero(&keyPtr, strideof(keyPtr.dynamicType))
testString.getCString(&keyPtr, maxLength: strideof(keyPtr.dynamicType), encoding: NSUTF8StringEncoding)
print(keyPtr)


On 32-bit devices (iPad 2, iPad 4) this logs:

[109, 121, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]


while on 64-bit devices (iPhone 6, Macbook Pro i7) this logs:

[109, 121, 84, 101, 115, 116, 83, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]


The 64-bit case is the correct result, while the 32-bit result does not.

I run into the same issue with
withCString
as well:

testString.withCString({
print($0)
})


On a 32-bit device this logs
0x7a992094
while a 64-bit device logs
0x00007f853c123760
.

How can I make the result of
getCString
or
withCString
the same across all architectures? Is this an issue with the size of
CChar
or arrays on the different architectures?

Answer

The bad point is this: strideof(keyPtr.dynamicType) It is the same as strideof(Array<CChar>), and its value is 4 in 32-bit, 8 in 64-bit.

You need to modify your code like this:

bzero(&keyPtr, keyPtr.count) //<-this is not needed, as you are specifying `0` for `repeatedValue`.
testString.getCString(&keyPtr, maxLength: keyPtr.count, encoding: NSUTF8StringEncoding)
Comments