ComUtils.cs (2327B)
1 // Copyright (c) Microsoft Corporation. 2 // Licensed under the MIT License. 3 4 namespace Microsoft.Management.Deployment.Projection 5 { 6 using System; 7 using System.Runtime.InteropServices; 8 9 internal static class ComUtils 10 { 11 [DllImport("api-ms-win-core-com-l1-1-0.dll")] 12 private static extern unsafe int CoCreateInstance(ref Guid clsid, IntPtr outer, uint clsContext, ref Guid iid, IntPtr* instance); 13 14 /// <summary> 15 /// CLSCTX enumeration 16 /// https://docs.microsoft.com/en-us/windows/win32/api/wtypesbase/ne-wtypesbase-clsctx 17 /// </summary> 18 private enum CLSCTX : uint 19 { 20 CLSCTX_INPROC_SERVER = 0x1, 21 CLSCTX_LOCAL_SERVER = 0x4, 22 CLSCTX_ALLOW_LOWER_TRUST_REGISTRATION = 0x4000000 23 } 24 25 /// <summary> 26 /// CoCreateInstance function 27 /// https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cocreateinstance 28 /// </summary> 29 /// <param name="clsid">CLSID</param> 30 /// <param name="clsContext">CLSCTX</param> 31 /// <param name="iid">IID</param> 32 /// <returns>Interface pointer, or throw an exception if HRESULT was not successful.</returns> 33 private static unsafe IntPtr CoCreateInstance(Guid clsid, CLSCTX clsContext, Guid iid) 34 { 35 IntPtr instanceIntPtr; 36 int hr = CoCreateInstance(ref clsid, IntPtr.Zero, (uint)clsContext, ref iid, &instanceIntPtr); 37 Marshal.ThrowExceptionForHR(hr); 38 return instanceIntPtr; 39 } 40 41 /// <summary> 42 /// CoCreateInstance with an out-of-process context. 43 /// </summary> 44 /// <param name="clsid">CLSID</param> 45 /// <param name="iid">CLSCTX</param> 46 /// <param name="allowLowerTrustRegistration">Allow lower trust registration</param> 47 /// <returns><see cref="CoCreateInstance"/> ></returns> 48 public static IntPtr CoCreateInstanceLocalServer(Guid clsid, Guid iid, bool allowLowerTrustRegistration = false) 49 { 50 CLSCTX clsctx = CLSCTX.CLSCTX_LOCAL_SERVER; 51 if (allowLowerTrustRegistration) 52 { 53 clsctx |= CLSCTX.CLSCTX_ALLOW_LOWER_TRUST_REGISTRATION; 54 } 55 56 return CoCreateInstance(clsid, clsctx, iid); 57 } 58 } 59 }