using System.Runtime.InteropServices; namespace HardwareControl.Core.SampleAnalysis { /// /// 通过 DXGI 枚举本机显卡适配器,用于区分独立显卡与核心显卡。 /// DirectML 执行后端的 device_id 就是 DXGI 适配器序号,因此这里返回的 /// 可直接传给 AppendExecutionProvider_DML。 /// internal static class GpuAdapterEnumerator { /// 独立显卡的专用显存下限,低于该值视为核显。 private const ulong DiscreteMemoryThreshold = 1024UL * 1024 * 1024; private const uint AdapterFlagSoftware = 0x2; /// IDXGIFactory1::EnumAdapters1 在虚表中的槽位。 private const int EnumAdapters1VtableIndex = 12; /// IDXGIAdapter1::GetDesc1 在虚表中的槽位。 private const int GetDesc1VtableIndex = 10; private static readonly Guid IID_IDXGIFactory1 = new("770aae78-f26f-4dba-a829-253c83d1b387"); internal sealed record GpuAdapter( int Index, string Name, ulong DedicatedVideoMemory, bool IsSoftware); [DllImport("dxgi.dll")] private static extern int CreateDXGIFactory1(ref Guid riid, out IntPtr factory); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int EnumAdapters1Delegate( IntPtr self, uint index, out IntPtr adapter); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetDesc1Delegate(IntPtr self, out DxgiAdapterDesc1 desc); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct DxgiAdapterDesc1 { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string Description; public uint VendorId; public uint DeviceId; public uint SubSysId; public uint Revision; public UIntPtr DedicatedVideoMemory; public UIntPtr DedicatedSystemMemory; public UIntPtr SharedSystemMemory; public uint LuidLowPart; public int LuidHighPart; public uint Flags; } /// /// 按硬件使用类型解析可用的显卡适配器。 /// 指定类型的显卡不存在时退回另一类显卡,完全没有可用显卡时返回 false。 /// public static bool TryResolve( HardwareUsageType usageType, out GpuAdapter adapter) { adapter = null!; if (usageType == HardwareUsageType.Cpu) { return false; } var devices = Enumerate() .Where(item => !item.IsSoftware) .ToList(); if (devices.Count == 0) { return false; } var discrete = devices .Where(item => item.DedicatedVideoMemory >= DiscreteMemoryThreshold) .OrderByDescending(item => item.DedicatedVideoMemory) .ToList(); var integrated = devices .Where(item => item.DedicatedVideoMemory < DiscreteMemoryThreshold) .OrderBy(item => item.DedicatedVideoMemory) .ToList(); var preferred = usageType == HardwareUsageType.DiscreteGpu ? discrete.Concat(integrated).FirstOrDefault() : integrated.Concat(discrete).FirstOrDefault(); adapter = preferred!; return adapter is not null; } /// 枚举全部 DXGI 适配器(包含软件适配器),失败时返回空列表。 public static IReadOnlyList Enumerate() { var adapters = new List(); IntPtr factory = IntPtr.Zero; try { var factoryId = IID_IDXGIFactory1; if (CreateDXGIFactory1(ref factoryId, out factory) < 0 || factory == IntPtr.Zero) { return adapters; } var enumAdapters1 = GetVtableDelegate( factory, EnumAdapters1VtableIndex); for (uint index = 0; ; index++) { if (enumAdapters1(factory, index, out var adapter) < 0 || adapter == IntPtr.Zero) { break; } try { var getDesc1 = GetVtableDelegate( adapter, GetDesc1VtableIndex); if (getDesc1(adapter, out var desc) >= 0) { adapters.Add(new GpuAdapter( (int)index, desc.Description ?? string.Empty, desc.DedicatedVideoMemory.ToUInt64(), (desc.Flags & AdapterFlagSoftware) != 0)); } } finally { Marshal.Release(adapter); } } } catch { // DXGI 不可用(老系统/远程会话限制)时返回空列表,调用方回退 CPU。 } finally { if (factory != IntPtr.Zero) { Marshal.Release(factory); } } return adapters; } private static T GetVtableDelegate(IntPtr instance, int vtableIndex) where T : Delegate { var vtable = Marshal.ReadIntPtr(instance); var method = Marshal.ReadIntPtr(vtable, vtableIndex * IntPtr.Size); return Marshal.GetDelegateForFunctionPointer(method); } } }