2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C の配列を Swift が Tuple として扱うのが面倒なのを倒す

Last updated at Posted at 2019-11-29

課題

Swift から C のライブラリを利用している際に、C の固定長配列を扱うのは少し煩わしいです。
なぜなら、Swift では Tuple として扱われるからです。
Tuple は Iteratable でないため、要素の参照に困ります。これをどうするか?

対応

方法1: reflection で倒す

https://qiita.com/codelynx/items/83f4b3829267d8d25b07 で述べられているように、reflection で Tuple を Array に変換する方法。
問題なくいけます。ただし、reflection は Compiler にとって負荷が高いため、積極的に使いたい方法とは言えないです。

方法2: ポインタで倒す

var foo_list = func_with_c()
let ptr = UnsafeMutablePointer<Foo>(&foo_list.foo.0)

// "固定長"のサイズをベタに書く。例えば長さが 34 だと知っているとする。
for i in 0..<34 {
    let foo = ptr[i]
    print(foo)
}

var を使うことになるのが嬉しくないのですが、reflection を行わないので Compiler に優しいです。
特段の理由が無ければこう書くことが多いのかな..?と思っています。

参考: Swift Foundation UUID implement

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?