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

Hooman Mehr hooman at mac.com
Thu Apr 27 20:56:51 CDT 2017


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

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. 

> On Apr 27, 2017, at 4:38 PM, Rick Mann via swift-users <swift-users at swift.org> wrote:
> 
> 
>> On Apr 27, 2017, at 01:48 , Alex Blewitt <alblue at apple.com> wrote:
>> 
> ...
> 
>> The let constant may not even be stored in a single place; if it's known to be constant it can be in-lined at the point of use and potentially unpacked and dead code elimination throw away the unused members, for example.
>> 
>> If you want to pass in a let constant into the pointer, you can create a copy of it locally in a local variable and then use that instead. However this will be in the local scope, so the pointer isn't valid after it returns.
> 
> Ah, so this brings up another issue, then. Many of the calls in the C library take a pointer to some memory and hang on to it, filling it in at a later point (they make network requests). I've been doing it like this, and it's been working, but I wonder if this is fragile:
> 
> class
> MyClass
> {
>    func
>    execute()
>    {
>        self.dataBuffer = Data(count: kLGSImageDataSize)
>        precondition(self.dataBuffer != nil, "Unable to allocate image buffer (\(kLGSImageDataSize) bytes)")
> 
>        var params = c_library_params_t()
>        params.data_capacity = self.dataBuffer!.count
> 
>        self.dataBuffer?.withUnsafeMutableBytes
>            { (inBuffer) -> Void in
>                //  This call returns immediately, but assumes
>                //  it can write to inBuffer later…
> 
>                self.request = c_library_call(&params, inBuffer)
>            }
> 
>        if self.request == nil
>        {
>            //  Error
>        }
>    }
> 
>    var             dataBuffer:     Data?
> }
> 
> 
> -- 
> Rick Mann
> rmann at latencyzero.com
> 
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list