How do you restore Swift class reference from UnsafeRawPointer?

When you've passed a reference to some Swift class instance into C function as UnsafeRawPointer, how could you restore class instance from this UnsafeRawPointer when C function passes it back to Swift?

import Foundation

class C {
	func selfToPointer() -> UnsafeRawPointer! {
		return UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque())
	}
	
	func selfFromPointer(this: UnsafeRawPointer!) -> C {
		return ???
		//return this.assumingMemoryBound(to: C.self).pointee
		// return this.load(as: C.self)
	}
	
	func check() {
		print("1. self == \(self)")
		
		let this:UnsafeRawPointer! = selfToPointer()
		print("2, this == \(String(describing: this))")
		
		let c:C = selfFromPointer(this: this)

		print("3, c == \(String(describing: c))")
	}
}

You can use Unmanaged<C>.fromOpaque(this).takeUnretained() More details can be found here mikeash.com: Friday Q&A 2017-08-11: Swift.Unmanaged

1 Like

Thanks, but this doesn't work..

I'm on Xcode15.4 (15F31d), if this matters

Works with

Unmanaged<C>.fromOpaque(this).takeUnretainedValue()

Thank you very much for your help!

1 Like