How to allocate -> send -> receive -> cast -> deallocate UnsafeRawPointer from extension to app?

▼魔方 西西 提交于 2019-12-02 11:01:15

问题


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 *).



来源:https://stackoverflow.com/questions/58226007/how-to-allocate-send-receive-cast-deallocate-unsaferawpointer-from-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!