Swift - Interoperability with c lang
The function is shown below obtains the machine model by calling the sysctlbyname function.
func getModelNameBySysCtl() -> String{
let name = "hw.machine"
var size: Int = 0
var result: String = ""
var funcRet: Int32 = -1
sysctlbyname(
name,
nil,
&size,
nil,
0
)
if size > 0 {
let valuePointer = UnsafeMutablePointer<CChar>.allocate(capacity: size)
valuePointer.initialize(to: 0)
funcRet = sysctlbyname(
name,
valuePointer,
&size,
nil,
0
)
if funcRet == 0{
result = String(cString: valuePointer)
}
valuePointer.deinitialize(count: size)
valuePointer.deallocate()
}
return result
}
Points of the above code
- String to UnsafePointer<CChar>
- Manage UnsafeMutablePointer<CChar>