苹果系统。如何以编程方式获取 CPU 温度
macOS. How to get CPU temperature programmatically
我需要使用 Swift 获取 CPU 温度,但我找不到任何信息,除了 this。
我认为我应该使用 IOKit.framework,但同样没有太多关于它的信息。
使用 https://github.com/lavoiesl/osx-cpu-temp/blob/master/smc.c 我让它工作了。你必须做几件事:
将 main()
简化为其他内容:
double calculate()
{
SMCOpen();
double temperature = SMCGetTemperature(SMC_KEY_CPU_TEMP);
SMCClose();
temperature = convertToFahrenheit(temperature);
return temperature;
}
编写一个 ObjC 包装器:
#import "SMCObjC.h"
#import "smc.h"
@implementation SMCObjC
+(double)calculateTemp {
return calculate();
}
@end
将 header 添加到您的 Swift 桥接 header。
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "SMCObjC.h"
如果应用程序被沙盒化,为 AppleSMC 添加安全豁免:
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.files.user-selected.read-only</key>
<true/>
<key>com.apple.security.temporary-exception.sbpl</key>
<array>
<string>(allow iokit-open)</string>
<string>(allow iokit-set-properties (iokit-property "AppleSMC"))</string>
<string>(allow mach-lookup (global-name "com.apple.AssetCacheLocatorService"))</string>
</array>
</dict>
</plist>
从 Swift 调用它。
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let temp = SMCObjC.calculateTemp()
print("I got \(temp) in swift")
}
}
我需要使用 Swift 获取 CPU 温度,但我找不到任何信息,除了 this。
我认为我应该使用 IOKit.framework,但同样没有太多关于它的信息。
使用 https://github.com/lavoiesl/osx-cpu-temp/blob/master/smc.c 我让它工作了。你必须做几件事:
将 main()
简化为其他内容:
double calculate()
{
SMCOpen();
double temperature = SMCGetTemperature(SMC_KEY_CPU_TEMP);
SMCClose();
temperature = convertToFahrenheit(temperature);
return temperature;
}
编写一个 ObjC 包装器:
#import "SMCObjC.h"
#import "smc.h"
@implementation SMCObjC
+(double)calculateTemp {
return calculate();
}
@end
将 header 添加到您的 Swift 桥接 header。
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "SMCObjC.h"
如果应用程序被沙盒化,为 AppleSMC 添加安全豁免:
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.files.user-selected.read-only</key>
<true/>
<key>com.apple.security.temporary-exception.sbpl</key>
<array>
<string>(allow iokit-open)</string>
<string>(allow iokit-set-properties (iokit-property "AppleSMC"))</string>
<string>(allow mach-lookup (global-name "com.apple.AssetCacheLocatorService"))</string>
</array>
</dict>
</plist>
从 Swift 调用它。
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let temp = SMCObjC.calculateTemp()
print("I got \(temp) in swift")
}
}