[swift-users] C Pointers and Memory

Zhao Xin owenzx at gmail.com
Fri Jul 29 04:40:19 CDT 2016


Have you read
https://developer.apple.com/library/tvos/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-ID17
 ?

Zhaoxin

On Fri, Jul 29, 2016 at 4:55 PM, James Campbell via swift-users <
swift-users at swift.org> wrote:

> ​Do you know of any resources to brush up on the pointer aspect of swift ?
>>
> *___________________________________*
>
> *James⎥Head of Trolls*
>
> *james at supmenow.com <james at supmenow.com>⎥supmenow.com
> <http://supmenow.com>*
>
> *Sup*
>
> *Runway East *
>
> *10 Finsbury Square*
>
> *London*
>
> * EC2A 1AF *
>
> On 29 July 2016 at 09:10, Dmitri Gribenko <gribozavr at gmail.com> wrote:
>
>> On Fri, Jul 29, 2016 at 12:55 AM, James Campbell <james at supmenow.com>
>> wrote:
>> > So this:
>> >
>> > if let data = someArrayGeneratingFunction() {
>> >   cFunction(UnsafeMutablePointer(data))
>> > }
>> >
>> > Has issues with the array passed to c getting corrupted, but this
>> doesn't:
>> >
>> > let data = someArrayGeneratingFunction()
>> >
>> > if let data = data {
>> >   cFunction(UnsafeMutablePointer(data))
>> > }
>>
>> Neither piece of code is guaranteed to work.  (You are just getting
>> lucky that the second one happens to work.)  Array-to-pointer
>> conversion only extends the lifetime of the array until the immediate
>> function call returns.  So after UnsafeMutablePointer(data) returns,
>> the array can be freed.
>>
>> Use someArrayGeneratingFunction.withUnsafeMutableBuffer { ... } instead.
>>
>> Dmitri
>>
>> --
>> main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
>> (j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/
>>
>
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160729/c1695d72/attachment.html>


More information about the swift-users mailing list