-->

How to allocate -> send -> receive -> cast -> deal

2020-04-20 08:07发布

问题:

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

  1. Add the CFNotificationCenterAddObserver observer in the app code
  2. Save sending object in UserDefaults(suitename:)
  3. Send the didObjectChanged notification through CFNotificationCenterPostNotification code
  4. Catch didObjectChanged notification in CFNotificationCallback in the app code
  5. Read sending object from UserDefaults(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 *).