首页 > 解决方案 > 如何在 Xamarin 中获取 iOS 设备 CPU 架构?

问题描述

UIKit.UIDevice.CurrentDevice在我的 Xamarin iOS 应用程序中,我可以从实例中获取许多设备特征,例如型号、系统名称等。但是,我没有看到任何获取类上的 CPU 架构(x86、arm 等)的方法。

How can I get the iOS device CPU architecture in runtime shows a way to get this information using Objective C. 我想知道是否有办法使用任何预定义的 Xamarin 类在 C# 中获取 CPU 信息。

标签: xamarin.ios

解决方案


在您的 iOS 项目中使用此类创建一个新文件:

public static class DeviceInfo
{
    public const string HardwareSysCtlName = "hw.machine";

    public static string HardwareArch { get; private set; }

    [DllImport(ObjCRuntime.Constants.SystemLibrary)]
    static internal extern int sysctlbyname([MarshalAs(UnmanagedType.LPStr)] string property, IntPtr output, IntPtr oldLen, IntPtr newp, uint newlen);

    static DeviceInfo()
    {
        var pLen = Marshal.AllocHGlobal(sizeof(int));
        sysctlbyname(HardwareSysCtlName, IntPtr.Zero, pLen, IntPtr.Zero, 0);

        var length = Marshal.ReadInt32(pLen);

        var pStr = Marshal.AllocHGlobal(length);
        sysctlbyname(HardwareSysCtlName, pStr, pLen, IntPtr.Zero, 0);

        HardwareArch = Marshal.PtrToStringAnsi(pStr);
    }
}

推荐阅读