【问题标题】:swift 4 access C struct values in libraryswift 4 访问库中的 C 结构值
【发布时间】:2017-08-21 16:26:43
【问题描述】:

我正在尝试访问存储在 Aubio 库中的 C 值,并相信这是我访问 Struct 值的方式。

该库有 C Struct 和 fvec_get_data 函数:

typedef struct {
  uint_t length;  /**< length of buffer */
  smpl_t *data;   /**< data vector of length ::fvec_t.length */
} fvec_t;

//in fvec.c

smpl_t * fvec_get_data(const fvec_t *s) {
  return s->data;
}

返回 swift 然后我按照建议读入数据:

            let oout = new_fvec(n_coefs)
            let c = new_aubio_mfcc(win_s, n_filters, n_coefs, samplerate);
            var read: uint_t = 0

            var dataStore = [smpl_t]()

                while (true) {
                    aubio_source_do(b, a, &read)
                    aubio_mfcc_do(c, iin, oout)

                    dataStore.append(fvec_get_data(oout).pointee)
                    total_frames += read

                    if (read < hop_size) { break }
                }

但是,这不会检索所有数据,仅检索数组中的第一个值。相比之下,在 while 循环中,您可以调用:

 fvec_print(oout) // this prints out ALL values not just the first

...

查看执行此操作的c code

void fvec_print(const fvec_t *s) {
  uint_t j;
  for (j=0; j< s->length; j++) {
    AUBIO_MSG(AUBIO_SMPL_FMT " ", s->data[j]);
  }
  AUBIO_MSG("\n");
}

非常感谢任何有关如何将所有值导入 Swift 的建议。

【问题讨论】:

    标签: ios swift struct swift4 swift-structs


    【解决方案1】:

    fvec_get_data(oout)out.data一样,都是指向第一个的指针 元素,而out.data.pointee 只是第一个元素本身。

    就像在 C 代码中一样,您可以使用循环遍历所有数据元素

    if let data = fvec_get_data(oout) { 
        for j in 0..<Int(n_coefs) {
            dataStore.append(data[j])
        }
    }
    

    这可以通过创建UnsafeBufferPointer 来简化 这是Sequence:

    if let data = fvec_get_data(oout) { 
        let buffer = UnsafeBufferPointer(start: data, count: Int(n_coefs))
        dataStore.append(contentsOf: buffer)
    }
    

    【讨论】:

    • 谢谢,首先我得到了“UnsafeMutablePointer?”类型的值没有成员“长度”。对于第二个选项,我得到 'UnsafeMutablePointer?' 类型的值没有成员“数据”
    猜你喜欢
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2022-01-18
    • 2018-12-03
    • 2020-03-15
    • 1970-01-01
    相关资源
    最近更新 更多