如何分配->发送->收到->演员->将UnsafeRawPointer从扩展名分配到应用程序? [英] How to allocate -> send -> receive -> cast -> deallocate UnsafeRawPointer from extension to app?
问题描述
我是UnsafeRawPointer
的新手.
如我所知,我需要在扩展程序中分配不安全的内存,并将指针发送到我的应用程序,该应用程序必须进行强制转换和释放.
以下是我想做的草图.
我想从Safari扩展程序发送string message
并通过CFNotificationCenterGetDarwinNotifyCenter
在应用程序中接收它,该怎么做?
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)
主要问题?
- 发送字符串使用哪种类型?
- 如何正确分配内存?
- 如何在观察者中将其转换为String?
- 如何正确释放内存?
- What type use to send String?
- How to allocate memory right?
- How to cast it to String in observer?
- How to deallocate memory right?
- 在应用程序代码 在应用程序
- 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:)
Main questions?
推荐答案
感谢@MartinR,我得到了所有有关我问题的答案.
Thanks @MartinR, I got all answers on my questions.
我们无法通过CFNotificationCenterPostNotification
发送对象,因此我们需要使用Darwin
和UserDefaults(suitename:)
组合.
We can't send an object though CFNotificationCenterPostNotification
so we need to use Darwin
and UserDefaults(suitename:)
combination.
题外话
Off-topic
Question Why do we use UnsafeRawPointer
? sample
答案 CFNotificationCenterPostNotification
实际上是一个C function
,并且回调也是一个纯C function
. C
对Swift types
或instance pointers
一无所知.这就是为什么object参数是UnsafeRawPointer
(与void *
等效的Swift
)的原因.
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 *
).
这篇关于如何分配->发送->收到->演员->将UnsafeRawPointer从扩展名分配到应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!