[swift-users] Passing a pointer to self to C function

John Brownie john_brownie at sil.org
Fri Sep 30 06:58:06 CDT 2016


Thanks! That works just as it should. It's all compiling and unit tests 
are passing, so I can move on now.
> Mike Ferenduros <mailto:mike.ferenduros at gmail.com>
> 30 September 2016 at 14:14
> The way to do this is via Unmanaged:
>     let raw = Unmanaged.passUnretained(expat).toOpaque()
> gets you an UnsafeMutableRawPointer you can pass into C functions. You 
> can turn this back into an ExpatSwift with
>     let expat = 
> Unmanaged<ExpatSwift>.fromOpaque(raw).takeUnretainedValue()
>
> There are also retained variants that will add or remove a reference 
> to the object in question.
> Basically, if you know that the pointer won't outlive the thing it 
> references, you want the unretained variants. This is usually what you 
> want when you're wrapping C APIs with callbacks, especially if 
> callbacks happen synchronously.
>
> On the other hand, if the pointer lives independently of the Whatever 
> then you may want to
>  - create the pointer with passRetained(), which will keep the object 
> it points to alive
>  - access the object with take*Un*retainedValue() (so you don't 
> prematurely release your reference to it), and
> - call release() on it when you're done with it.
> If you forget the 3rd step then you're leaking memory, and if you 
> miscalculate and do it twice then you crash.
>
> Or if you're just passing a pointer from A to B one time, you can use 
> passRetained() + takeRetainedValue().
>

-- 
John Brownie
In Finland on furlough from SIL Papua New Guinea
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160930/a3c41e94/attachment.html>


More information about the swift-users mailing list