苹果系统.如何以编程方式获取CPU温度 [英] macOS. How to get CPU temperature programmatically

查看:105
本文介绍了苹果系统.如何以编程方式获取CPU温度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Swift获取CPU温度,但是除了

I need to get CPU temperature using Swift, but I can't find any information except for this.

我认为我应该使用IOKit.framework,但同样也没有太多信息.

I think that I should use IOKit.framework but again there's no much information about it.

推荐答案

using

using https://github.com/lavoiesl/osx-cpu-temp/blob/master/smc.c I got it to work. You have to do a few things:

main()简化为其他内容:

double calculate()
{
    SMCOpen();
    double temperature = SMCGetTemperature(SMC_KEY_CPU_TEMP);
    SMCClose();
    temperature = convertToFahrenheit(temperature);
    return temperature;
}

写一个ObjC包装器:

Write an ObjC wrapper:

#import "SMCObjC.h"
#import "smc.h"   
@implementation SMCObjC

+(double)calculateTemp {
    return calculate();
}

@end

将标题添加到您的 Swift 桥接头.

Add the header to your Swift bridging header.

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "SMCObjC.h"

如果应用已沙箱化,请为AppleSMC添加安全豁免:

If the app is sandboxed, add a security exemption for 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")
    }
}

这篇关于苹果系统.如何以编程方式获取CPU温度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆