我可以使用python从SCDynamicStoreCopyConsoleUser获取用户名,UID和GID:
#!/usr/bin/python
from SystemConfiguration import SCDynamicStoreCopyConsoleUser
cfuser = SCDynamicStoreCopyConsoleUser( None, None, None )
print cfuser[0] # Returns console user, e.g.: myUsername
print cfuser[1] # Returns console user’s UID, e.g.: 501
print cfuser[2] # Returns console user’s GID, e.g.: 20
如何使用Swift获得相同的回报?
SCDynamicStoreCopyConsoleUser的快速声明
func SCDynamicStoreCopyConsoleUser(_ store: SCDynamicStore!,
_ uid: CMutablePointer<uid_t>,
_ gid: CMutablePointer<gid_t>) -> Unmanaged<CFString>!
我的快速通话
var uid: CMutablePointer<uid_t>!
var gid: CMutablePointer<gid_t>!
var cfuser: NSArray = [SCDynamicStoreCopyConsoleUser(nil,uid,gid)]
// the return has only one element containing the username
答案 0 :(得分:1)
Swift函数SCDynamicStoreCopyConsoleUser
采用CMutablePointer<uid_t>
参数,这意味着您必须传递uid_t
变量的地址。
您还应检查呼叫是否成功(否则返回nil
),
你呢
必须转换返回的非托管对象,如中所述
Working with Cocoa Data Types:
import SystemConfiguration
var uid: uid_t = 0
var gid: gid_t = 0
if let theResult = SCDynamicStoreCopyConsoleUser(nil, &uid, &gid) {
let name = theResult.takeUnretainedValue()
println("name = \(name), uid = \(uid), gid = \(gid)")
} else {
println("failed")
}