【问题标题】:Objective-C++ and Swift - nested structs in bridging headerObjective-C++ 和 Swift - 桥接头中的嵌套结构
【发布时间】:2020-11-22 12:44:29
【问题描述】:

请帮助我解决以下问题。我正在使用 swift 参数解析器库https://github.com/apple/swift-argument-parser

假设我在某个 swift 文件中有这个 swift 代码:

@objc public class Math: NSObject, ParsableCommand {
    static var configuration = CommandConfiguration(
        abstract: "A utility for performing maths.",
        subcommands: [Add.self],
        defaultSubcommand: Add.self)
}
    
extension Math {
    struct Add: ParsableCommand {
        static var configuration = CommandConfiguration(abstract: "Print the sum of the values.")        
        mutating func run() {
            print("0")
        }
    }
}

` 我想调用一个名为“func”的objective-c ++函数,其参数类型为Math.Add,就像main.swift文件中的那样:

var status: Int32 = 0
do {
    // try to parse application arguments
    var args = try Math.parseAsRoot()
    switch args {
        case let args as Math.Add:
            status = func(args)
        default:
            try args.run()
        }
} catch {
    //Some code...
}

函数的签名应该是什么以及桥接头文件应该是什么样子?我的签名是:

extern "C" int func(Math.Add *args);

而我的桥接头是这样的:

#ifndef __BRIDGING_HEADER_H__
#define __BRIDGING_HEADER_H__



@class Math;


#ifdef __cplusplus
   extern "C" {
#endif
   int func(Math.Add  *args);
#ifdef __cplusplus
    }
#endif

#endif /* __BRIDGING_HEADER_H__ */

但是它不起作用并且桥接头没有编译(Xcode 写错误:接口类型'Math' 不能按值传递;你忘记了'Math' 中的*?

【问题讨论】:

    标签: swift objective-c++ bridging-header


    【解决方案1】:

    Objective-C(++) 不支持嵌套类型,如果你想在 Swift 上保留嵌套结构,你可以做的是为 Objective-C 导出一个非嵌套类型:

    extension Math {
        @objc(Math_Add) // or MathAdd, or whatever name you like
        struct Add: ParsableCommand {
    

    ,然后可以在您的标题中引用:

    int func(Math_Add  *args);
    

    作为旁注,我还将 func 函数的名称更改为不与 Swift 关键字冲突的名称。即使您能够调用它,它也会让其他阅读您的代码的人感到困惑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多