I need to get a pointer to self which is passed to a C function. The C API will later call a callback method and pass back this reference which I can then use to get an instance to my class back.
The code below shows a simple example of what I am trying to do. ptrToSelf() should return an UnsafeMutableRawPointer which I can then pass to the C function. This is later on used to get the instance to the class back.
I can get a pointer to the instance of my class, but not to self.
What should I do in the implementation of ptrToSelf()?
class MyClass {
func doSometing() {
print("I'm trying.")
}
func ptrToSelf() -> UnsafeMutableRawPointer {
return Unmanaged.passUnretained(self).toOpaque()
}
}
var myClass = MyClass()
//let rawPtr = UnsafeMutableRawPointer(&myClass) // <-- This works.
let rawPtr = myClass.ptrToSelf() // <-- This does not work.
let classPtr = rawPtr.bindMemory(to: MyClass.self, capacity: 1)
classPtr.pointee.doSometing()