[swift-users] Why does withUnsafePointer(to:) require a var argument?

Hooman Mehr hooman at mac.com
Thu Apr 27 22:00:48 CDT 2017


> On Apr 27, 2017, at 7:31 PM, Rick Mann <rmann at latencyzero.com> wrote:
> 
> 
>> On Apr 27, 2017, at 18:56 , Hooman Mehr <hooman at mac.com> wrote:
>> 
>> You should be able to type your `dataBuffer ` as [Int8] (Byte array). Then you won’t need `withUnsafeMutableBytes`. You can simply call it like this:
>> 
>> self.request = c_library_call(&params, dataBuffer) // Call as if it is a C array
> 
> Hmm. I'm not able to pass self.dataBuffer or self.dataBuffer! to the call. It's expecting `UnsafeMutableRawPointer!`.
> 

Oh, if the original C declaration is not `const`, it needs & prefix:

self.request = c_library_call(&params, &dataBuffer)

Also let me clarify that documentation states that it does not guarantee the pointer will stay valid after the call returns, but if the optimizations are on, and you don’t mess with the array, I think it should work. Basically, I wanted to point out an alternative to withUnsafe… stuff, not to address your validity question.

>> 
>> It works because of C interoperability compiler magic.
>> 
>> As long as the instance holding `dataBuffer` is not deallocated and you have not resized the array, the pointer should remain valid. 
> 
> 
> -- 
> Rick Mann
> rmann at latencyzero.com
> 
> 



More information about the swift-users mailing list