如何在macOS捆绑软件之间传递数据?
例如:MyApp.app将数据发送到MyBundle.bundle中的函数或类初始化程序,该函数或类初始化程序对其执行自己的逻辑。它甚至可以返回一个值,然后MyApp.app可以对其进行进一步处理。
示例,一个Objective-C函数:
void initialise(unsigned int frameCount) {…} // not a class initialiser btw
我尝试过:
在MyBundle中声明一个类,然后使用Foundation.Bundle
将其加载到MyApp中:
let class = (Bundle(url: url)!.classNamed("MyClass")! as! NSObject.Type).init()
// class is an instance of NSObject, but I can override the `init()` method
// (in MyBundle) to do whatever. I have not found a way to implement an
// initialiser with parameters, and it still be recognised here.
在MyBundle中声明一个函数,然后使用CFBundleGetFunctionPointerForName
进行检索。
var bundles = CFBundleCreateBundlesFromDirectory(kCFAllocatorDefault, bundleDirectory, bundleExtension)! as Array
var bundle1 = bundles.first! as! CFBundle
var untypedFunctionPointer = CFBundleGetFunctionPointerForName(bundle, "initialise" as CFString)!
let imp = unsafeBitCast(untypedFunctionPointer, to: IMP.self)
let function = unsafeBitCast(imp, to: (@convention(c)(CUnsignedInt) -> Void).self)
// If I specify parameters here, pass them in below, then try to use them in my objective c function, I get exc_bad_access.
function(CUnsignedInt(1.0)) // Will work only when not trying to access parameters in the original objective c function.
// Whatever @convention(c) function signature I use, the parameters are unusable in Objective C.
两者的关键问题是我无法将数据作为参数传递。因此,打印语句将起作用,但不能使用参数。
基于您的问题Call Swift function from Bundle和https://stackoverflow.com/a/56281093/5329717中的注释,我想您是在Swift中通过UnsafeBufferPointer
参数动态调用函数指针或Objective-C方法之后。