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()
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.
You have the first part of this right but you’re definitely off in the weeds with regards the second part. You can find instructions for fixing that in this post.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"