macOS捆绑包之间的双向数据交换(swift)
如何在macOS捆绑包之间传递数据 例如:MyApp.app将数据发送到MyBundle.bundle中的函数或类初始化器,后者对其执行自己的逻辑。它甚至可以返回一个值,MyApp.app可以进一步处理该值 例如,MyBundle中的函数(未嵌套在任何其他声明中): 我试过:macOS捆绑包之间的双向数据交换(swift),swift,bundle,foundation,Swift,Bundle,Foundation,如何在macOS捆绑包之间传递数据 例如:MyApp.app将数据发送到MyBundle.bundle中的函数或类初始化器,后者对其执行自己的逻辑。它甚至可以返回一个值,MyApp.app可以进一步处理该值 例如,MyBundle中的函数(未嵌套在任何其他声明中): 我试过: 在MyBundle中声明一个类,然后使用Foundation.Bundle将其加载到MyApp中: let class = (Bundle(url: url)!.classNamed("MyClass")! as! NS
- 在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中声明函数并使用
检索它CbundleGetFunctionPointerForName
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.
UnsafeBufferPointer
将创建一个副本,因此为了进行互操作,我建议切换到OpaquePointer
假设函数指向带有签名的指针大小写void cFunction(void*arg)
:
假设静态目标-c方法:
let receiverClass = NSClassFromString("SomeClass")
let selector: Selector = NSSelectorFromString("selectorArg:")
let methodIMP: IMP! = method_getImplementation(class_getClassMethod(receiverClass, selector))
unsafeBitCast(methodIMP,to:(@convention(c)(AnyClass?,Selector,OpaquePointer)->Any).self)(receiverClass,selector, bufferArg)
为您提供的C签名
void initialise(unsigned int frameCount);
试试这个:
let imp = unsafeBitCast(functionToPointerAddress, to: IMP.self)
unsafeBitCast(imp,to:(@convention(c)(Int)->Void).self)(1)
@Div请在您的问题中包含原始C函数/目标C方法签名。非常感谢您展示此技术。结果表明,崩溃是使用与Objy-C和基金会不兼容的类型的结果,所以现在我只使用NSCONT、NSArray等。
void initialise(unsigned int frameCount);
let imp = unsafeBitCast(functionToPointerAddress, to: IMP.self)
unsafeBitCast(imp,to:(@convention(c)(Int)->Void).self)(1)