I am new in UnsafeRawPointer
.
As I got I need to allocate unsafe memory in my extension and send pointer to my app where has to cast and release it.
Below is a sketch of what I want to do.
I'd like to send a string message
from Safari extension and receive it in app by CFNotificationCenterGetDarwinNotifyCenter
, how to do it?
let center = CFNotificationCenterGetDarwinNotifyCenter()
CFNotificationCenterAddObserver(center, nil, { (_, observer, name, message, _) -> Void in
//message as String???
}, Self.action, nil, .deliverImmediately)
var message = "some text"
CFNotificationCenterPostNotification(center, .init(action), message, nil, true)
Main questions?
- What type use to send String?
- How to allocate memory right?
- How to cast it to String in observer?
- How to deallocate memory right?
Thanks @MartinR, I got all answers on my questions.
We can't send an object though
CFNotificationCenterPostNotification
so we need to useDarwin
andUserDefaults(suitename:)
combination.Schema
CFNotificationCenterAddObserver
observer in the app codesending object
inUserDefaults(suitename:)
didObjectChanged
notification throughCFNotificationCenterPostNotification
codedidObjectChanged
notification inCFNotificationCallback
in the app codesending object
fromUserDefaults(suitename:)
Off-topic
Question Why do we use
UnsafeRawPointer
? sampleAnswer
CFNotificationCenterPostNotification
is actually aC function
, and the callback is also a pureC function
.C
knows nothing aboutSwift types
orinstance pointers
. That's why the object parameter is aUnsafeRawPointer
(theSwift
equivalent ofvoid *
).