LoginSignup
6
7

More than 5 years have passed since last update.

swift3でswift2.3で動いていたC構造体メンバ(Char配列)を読み込むコードが動かなかった件について

Posted at

下記のようなC構造体を、bridge経由でswiftから操作するとき、

cstruct.h
 #define MEM01_SIZE 255
 struct cstruct {
    char cstr01[MEM01_SIZE];
  } 

swift2では下記のようなコードで出来ていたが、swift3ではコンパイラエラーになっていた。

swift2.2.swift
var size: Int32 = 0
var cstruct = GetCStruct(&size)
let cstr01_str = withUnsafePointer(&cstruct.memory.cstr01)
{
 return String.fromCString(UnsafePointer($0))!
}

swift3では下記のようにすれば通った。

swift3.swift
var cstr01_str_tuple = cstruct?.pointee.cstr01
let cstr01_str = withUnsafePointer(to: &cstr01_str_tuple)
{
  return String(cString: UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self))
}

なんでこれで動くのかよく分かってなくて、解説はまだ書けないけど、とりあえず動いたのでメモ。

6
7
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
6
7