[英]How to call a Swift function with a callback from C
I am trying to write an iOS plugin for Unity, which requires the use of a bridge with a C layer.我正在尝试为 Unity 编写一个 iOS 插件,它需要使用带有 C 层的桥接器。
The plugin itself is written in Swift.插件本身是用 Swift 编写的。
Currently my implementation works like so:目前我的实现是这样的:
// Swift // Swift
@objc public class SomeClass {
@objc public func SomeFunction() -> String {
return "Hello"
}
}
// C // C
extern "C" {
void _someFunction() {
// I can access the Swift file using "[SomeClass shared]"
// This returns the "Hello" string correctly
NSString *helloMessage = [[SomeClass shared] SomeFunction];
}
}
This works, but now I need to make an async call which requires a callback from the Swift implementation.这可行,但现在我需要进行异步调用,这需要来自 Swift 实现的回调。
// Swift // Swift
@objc public class SomeClass {
@objc public func SomeFunction(completionHandler: (String) -> Void) {
// Gets called after some async operations
completionHandler(“hello”)
}
}
Is it possible to call this Swift function from the C layer and how would you do so?是否可以从 C 层调用此 Swift function ,你会怎么做?
// C // C
extern "C" {
void _someFunction() {
// ??????
}
}
If you set up bridging well then the call should be like如果您设置好桥接,那么呼叫应该是
void _someFunction() {
[[SomeClass shared] SomeFunctionWithCompletionHandler:^(NSString * _Nonnull value) {
NSLog(@"Result: %@", value);
}];
}
Btw, classes to be visible in Objective-C should be 'is-a' NSObject
, like顺便说一句,在 Objective-C 中可见的类应该是 'is-a'
NSObject
,比如
@objcMembers public class SomeClass: NSObject {
public static var shared = SomeClass()
public func SomeFunction() -> String {
return "Hello"
}
public func SomeFunction(completionHandler: (String) -> Void) {
// Gets called after some async operations
completionHandler("hello")
}
}
Tested with Xcode 13.2 / iOS 15.2使用 Xcode 13.2 / iOS 15.2 测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.