Search code examples
kotlinkotlin-multiplatformkotlin-native

How to use UnsafeMutableRawPointer in Kotlin/Native?


I am trying to implement an observer to the changes of UserDefaults for a given key in iOS part of Multi-platform library written with Kotlin/Native. The Swift signature of the function that I need to implement is:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)

But it seem that there is no mapping on Kotlin/Native side for UnsafeMutableRawPointer.

How can I achieve that? The code swift code that I would like to port to Kotlin is the following:

let globalDataStore = UserDefaults(suiteName: "global")

func setObserver() {
    globalDataStore?.addObserver(self, forKeyPath: "StringKey", options: NSKeyValueObservingOptions.new, context: nil)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    print("observeValue: \(change?[NSKeyValueChangeKey.newKey] ?? "NO VLAUE")");
}

Solution

  • As I found in the documentation, the Objective-C version of the observeValue method utilizes void * typed argument as a context. This type is being mapped to Kotlin/Native as a COpaquePointer(see this doc's Pointer types subsection). There is no UnsafeMutableRawPointer representation as K/N currently provides interoperability with the Objective-C only.