I am puzzled by this:
The compiler is doing something special here: It’s using the in-out &
marker to take your compression_stream
and turn it into an UnsafeMutablePointer<compression_stream>
. Alternatively, you could have passed streamPointer
. Then you wouldn’t need this special conversion
Is this what is meant by “passing streamPointer
”?
status = compression_stream_process(streamPointer, flags)
I sort of see why that might work, but if I do it,
case COMPRESSION_STATUS_ERROR
gets triggered at the switch statement. What am I missing? Could someone clarify? Thanks.
Edit 1:
This appears to be related, but honestly, I don’t understand the discussion. Indeed, when I wrote that I “sort of see why this might work” , I was under the apparently incorrect impression (as remarked in the link) that stream and streamPointer.pointee pointed to the same object.
Edit 2:
Indeed, this snippet confirms that stream and streamPointer.pointee are not pointing to the same thing:
withUnsafePointer(to: stream) { pointer_1 in
withUnsafePointer(to: streamPointer.pointee) {
pointer_2 in
print(pointer_1)
print(pointer_2)
print (pointer_1 == pointer_2) //false
}
}
This still leaves unanswered the question of why the original code works, and the alternative doesn’t. It’s all very mysterious to me.
Edit 3:
Of course they don’t point to the same thing: compression_stream is a struct, so saying
var stream = streamPointer.pointee
which is short for
var stream: compression_stream = streamPointer.pointee
is actually creating a new compression_stream struct out of whatever was stored in streamPointer. But at this point streamPointer is pointing to an uninitialized chunk of memory. How can this possibly work? Still very confused.
Edit 4:
After some experimentation, it seems to me that it is much clearer and cleaner to initialize the stream like this:
var dst:UInt8 = 0
var src: UInt8 = 0
var stream = compression_stream(dst_ptr: &dst, dst_size: 0, src_ptr: &src, src_size: 0, state: nil)
var status = compression_stream_init(&stream, streamOperation, streamAlgorithm)
guard status != COMPRESSION_STATUS_ERROR else {
print(“Oh, no!!”)
return nil
}
defer {
if compression_stream_destroy(&(stream)) == COMPRESSION_STATUS_ERROR {
print(“COMPRESSION_STATUS_ERROR”)
} else {
print(“Stream deinitialization OK”)
}
}
which works, and avoids all the pointee song and dance. Opinions?