x86/x64 CPUID in C#

后端 未结 7 971
谎友^
谎友^ 2020-11-28 03:18

Related to my other question, please help me debug \"An unhandled exception of type \'System.AccessViolationException\' occurred in Unknown Module. Additional information:

7条回答
  •  忘掉有多难
    2020-11-28 04:05

    Thanks to @antiduh for his solution. I'd change the Invoke signature a little bit for better usability as follows, so you don't need to allocate an get the result as a set of registers

        // This is a modification to https://stackoverflow.com/a/7964376/725903
        [UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
        private delegate void CpuIDDelegate(int level, IntPtr ptr);
    
        [StructLayout(LayoutKind.Sequential, Size = 16)]
        public struct CpuIdResult
        {
            public int Eax;
            public int Ebx;
            public int Ecx;
            public int Edx;
        }
    
        public CpuIdResult Invoke(int level)
        {
            CpuIdResult result;
            IntPtr buffer = Marshal.AllocHGlobal(16);
            try
            {
                this.cpuIdDelg(level, buffer);
                result = (CpuIdResult)Marshal.PtrToStructure(buffer, typeof(CpuIdResult));
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
            return result;
        }
    

提交回复
热议问题