Peter
Peter

Reputation: 11910

How to obtain iOS device CPU architecture in Xamarin?

In my Xamarin iOS application, I can obtain many device characteristics such as model, system name, etc. from UIKit.UIDevice.CurrentDevice instance. However, I don't see any method to obtain CPU architecture (x86, arm, etc.) on the class.

How can I get the iOS device CPU architecture in runtime shows a way to get this information using Objective C. I am wondering if there a way to get the CPU information in C# using any of the predefined Xamarin classes.

Upvotes: 0

Views: 418

Answers (2)

Brian Hong
Brian Hong

Reputation: 1084

Today, I found that this code works not only for Windows(UWP), but also for iOS With Xamarin:

System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString();

With iOS Simulator, RuntimeInformation has more information, like OSArchitecture, but with real iOS device, only ProcessArchitecture was available.

I used all available recent softwares: Xcode 12.4, Visual Studio for Mac 8.9 (1651), etc.

Upvotes: 0

J. Aguilar
J. Aguilar

Reputation: 194

Create a new file with this class on your iOS project:

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);
    }
}

Upvotes: 2

Related Questions