3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

インスタンスをUnsafeMutablePointerに変換して扱う

Last updated at Posted at 2016-02-22

CTRunDelegateRefを扱う上でインスタンスをUnsafeMutablePointerにする必要がある部分がでてきたので、下記の方法だとアプリもクラッシュせずエラーも出ずに動いたので書き残します。

let originalView = UIView()
print(originalView) //"UIView: 0x7fcd29f031a0"

//UnsafeMutablePointerに変換
let pointer = UnsafeMutablePointer<UIView>(Unmanaged.passRetained(originalView).toOpaque())

//UIView取得
let takeValue = Unmanaged<UIView>.fromOpaque(COpaquePointer(pointer)).takeRetainedValue()

print(takeValue) //"UIView: 0x7fcd29f031a0"
Sample
extension UIView {
    class func view(pointer pointer: UnsafeMutablePointer<Void>) -> UIView {
        return Unmanaged<UIView>.fromOpaque(COpaquePointer(pointer)).takeRetainedValue()
    }
}

class HogeView: UIView {
    func  createWidthCallback() -> CTRunDelegateGetWidthCallback {
        return {
            let view = UIView.view(pointer: $0)
            return view.bounds.size.width
        }
    }
}

CTRunDelegateGetWidthCallbackなどのtypealias@convention(c)が付加されているものでも、staticなメソッドでpointerから自身を取得するようにすればエラーは起こらなくなります。
逆にselfにアクセスするとエラーが起こります。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?