【问题标题】:C interoperability with SwiftC 与 Swift 的互操作性
【发布时间】:2016-04-15 22:21:32
【问题描述】:

我在我的 Swift 2.2 iOS 项目中包含了一个 C 结构。 C 结构通过头文件公开为:

   #define NUM_BINS 10;
   typedef struct
   {
       float bin_size;
       unsigned short counts[NUM_BINS];
       unsigned int cleanSamples;
       unsigned short compressCount;
       unsigned short totalSamples;
       bool isMature;
   } SD;

然后我尝试通过以下方式在 Swift 中声明这个结构:

    var counts: [UInt16] = [1,2,3,4,5,6,7,8,9,10]
    let sd = SD(bin_size: 500, counts: counts, cleanSamples: 0, compressCount: 0, totalSamples: 0, isMature: false)

但收到以下错误:

无法将类型 '[UInt16]' 的值转换为预期的参数类型 '(UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)'

我怎样才能把它从 C 翻译成 Swift?

谢谢!

【问题讨论】:

  • 试着去掉 UInt16 周围的括号
  • 如果你改用counts: &counts会发生什么?

标签: ios c arrays swift struct


【解决方案1】:

固定大小的 C 数组变成 Swift 元组,而不是 Swift 数组。 (请参阅here 了解一些不幸的后果。)所以不要

var counts: [UInt16] = [1,2,3,4,5,6,7,8,9,10]

你需要类似的东西

var counts = (1,2,3,4,5,6,7,8,9,10)

顺便说一句,我在 Apple 的官方文档中没有发现任何这样的说法。我不知道这是否是担心它在未来可能会改变的理由......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    相关资源
    最近更新 更多