苹果系统。如何以编程方式获取CPU温度

问题描述 投票:1回答:1

我需要使用Swift获得CPU温度,但除了this之外我找不到任何信息。

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

swift macos iokit
1个回答
7
投票

使用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")
    }
}

这是我的示例项目:

https://www.dropbox.com/sh/lpe9bm08s2ynoob/AAA-N_br7aqRxJRks53FYK0fa?dl=0

© www.soinside.com 2019 - 2024. All rights reserved.