Created
March 23, 2018 08:09
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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