This is a practical question, i'm sending a file by breaking it into trunks of, say, 1000 bytes
data = NSData.dataWithContentsOfFile(path)
var dataPackage : [Byte](count: 1000, repeatedValue: 0)
for offset = 0; offset < data.length; {
// omit some range check here
data.getBytes(&dataPackage, NSRange(location: offset, length: 1000))
send(dataPackage)
}
Everything was great, until I want to insert a sequence number into dataPackage, at position 0, so naturally, I would change the above to
data.getBytes(&dataPackage[1], NSRange(location: offset, length: 999))
It turned out that only 1 single element is copied to dataPackage. The rest 999 elements were copied to dont-know-where
My question is, 1) how to make this work, and 2) how array in swift is addressed, in such a way that &data[i] = &data + i (as shown in the 1st example) but &data[i+k] != &data[i] + k
Edit: I solved (1) by doing
data.getBytes(&dataPackage + 1, NSRange(location: offset, length: 999))
Question (2) remains
Do not
getBytes(&dataPackage[i] + k, ..)
, I think, this may causes "access violation"Consider this code:
MyStruct
is just a wrapper aroundArray
.myFunc
receives a mutable pointer and mutates the value of it.With this, when yo do:
outputs:
See?
somewhere
somewhere
somewhere
I don't know where
somewhere
is, though.When you do like:
outputs:
This time, my guess would be:
somewhere
corrupted
assomewhere + 1
somewhere
somewhere
corrupted
On the other hand, when you do:
This means:
ptr
as the pointer of the first element offoo
ptr
asptr + 1
ptr
As a result,
foo[1]
will be12
successfully as you did.Actually in-out(
&
) ofArray
is very special as mentioned in the document.Only the built-in
Array
has the last feature.So, when you pass
¬AnArrayLvalue
(including&array[i]
) toUnsafeMutablePointer<Type>
parameter, the length should be always1
, and you should not+
or-
it.