Skip to content

Instantly share code, notes, and snippets.

@oxycoder
Created March 23, 2018 08:09
Show Gist options
  • Save oxycoder/3c224a4d390f37264d5156b80312f49a to your computer and use it in GitHub Desktop.
Save oxycoder/3c224a4d390f37264d5156b80312f49a to your computer and use it in GitHub Desktop.
Convert C fixed char array to swift tuple and swift tuple to C char array
//
extension String {
/*
* Convert to String from Tuple
*/
static func fromTuple<T>(tuple:T) -> String? {
let reflection = Mirror(reflecting: tuple)
var arr : [Int8] = []
for child in reflection.children {
if let value = child.value as? Int8 {
arr.append(value)
}
}
return String(cString: UnsafePointer<CChar>(arr))
}
/*
* Convert String to Tupple Fixed size
*/
func toTuple<T>(tuple: inout T, size: Int) -> () {
let name: [UInt8] = [UInt8](self.utf8)
withUnsafeMutablePointer(to: &tuple, { (ptr) -> () in
memset(ptr, 0, size)
memcpy(ptr, name, name.count)
return
})
}
}
// Though we have Player struct import from Bridge Header
let player = Player()
"NewName".toTuple(tuple: &player.name, size: 23)
player.level = 10
print(player.name)
let otherName = ("W", "a", "l", "k", "e", "r")
let playerName: String = String.fromTuple(tuple: otherName)
print(playerName)
// Player.h
type struct Player {
char name[23];
int level;
} Player;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment