macOS. 如何以编程方式获取CPU温度

7

我需要使用Swift获取CPU温度,但除了这篇文章之外,我找不到其他任何信息。

我认为我应该使用IOKit.framework,但是关于它的信息也不多。

1个回答

13

使用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

将头文件添加到您的Swift桥接头文件中。

//
//  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 &quot;AppleSMC&quot;))</string>
        <string>(allow mach-lookup (global-name &quot;com.apple.AssetCacheLocatorService&quot;))</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")
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接