When operating a C structure like the one below from swift via bridge
cstruct.h
#define MEM01_SIZE 255
struct cstruct {
char cstr01[MEM01_SIZE];
}
In swift2, it was made with the following code, but in swift3, it was a compiler error.
swift:swift2.2.swift
var size: Int32 = 0
var cstruct = GetCStruct(&size)
let cstr01_str = withUnsafePointer(&cstruct.memory.cstr01)
{
return String.fromCString(UnsafePointer($0))!
}
In swift3, I passed by doing the following.
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))
}
I'm not sure why it works, so I can't write a commentary yet, but it worked for the time being, so make a note.
Recommended Posts