macOS捆绑包之间的双向数据交换(swift)

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

如何在macOS捆绑包之间传递数据

例如:MyApp.app将数据发送到MyBundle.bundle中的函数或类初始化器,后者对其执行自己的逻辑。它甚至可以返回一个值,MyApp.app可以进一步处理该值

例如,MyBundle中的函数(未嵌套在任何其他声明中):

我试过:

  • 在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.
    
两者的关键问题是我无法将数据作为参数传入。因此,print语句可以工作,但不能使用参数

编辑:接受答案显示调用函数指针的正确方法。我提到的崩溃是由于使用了未正确连接到C语言家族的类型造成的,所以请坚持使用NSNumber,NSCORT从基础库中被怀疑。

< P>根据您的问题和评论,我假设您在Swift中动态调用一个函数指针或Objy-C方法,用<代码> unSuffBuffer-Posivs/Cuff>参数。

首先,
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)