问题
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?
回答1:
Thanks @MartinR, I got all answers on my questions.
We can't send an object though CFNotificationCenterPostNotification
so we need to use Darwin
and UserDefaults(suitename:)
combination.
Schema
- Add the
CFNotificationCenterAddObserver
observer in the app code - Save
sending object
inUserDefaults(suitename:)
- Send the
didObjectChanged
notification throughCFNotificationCenterPostNotification
code - Catch
didObjectChanged
notification inCFNotificationCallback
in the app code - Read
sending object
fromUserDefaults(suitename:)
Off-topic
Question Why do we use UnsafeRawPointer
? sample
Answer CFNotificationCenterPostNotification
is actually a C function
, and the callback is also a pure C function
. C
knows nothing about Swift types
or instance pointers
. That's why the object parameter is a UnsafeRawPointer
(the Swift
equivalent of void *
).
来源:https://stackoverflow.com/questions/58226007/how-to-allocate-send-receive-cast-deallocate-unsaferawpointer-from-e