From dd5440456236d5dd670a260fb2750ba22c9b833a Mon Sep 17 00:00:00 2001 From: Joshua Larkin <70237359+j0shuams@users.noreply.github.com> Date: Mon, 4 Oct 2021 11:06:02 -0700 Subject: [PATCH 01/11] embed winrt.runtime --- src/Authoring/WinRT.Host.Shim/Module.cs | 10 +- src/Projections/Test/Module.cs | 2 +- .../TestHost.ProbeByClass/Module.cs | 2 +- src/Projections/Windows/Module.cs | 2 +- src/Tests/AuthoringTest/Module.cs | 2 +- src/WinRT.Runtime/AgileReference.cs | 43 +- src/WinRT.Runtime/Attributes.cs | 25 +- src/WinRT.Runtime/CastExtensions.cs | 27 +- src/WinRT.Runtime/ComWrappersSupport.cs | 36 +- src/WinRT.Runtime/ComWrappersSupport.net5.cs | 27 +- .../ComWrappersSupport.netstandard2.0.cs | 13 +- src/WinRT.Runtime/Context.cs | 5 +- src/WinRT.Runtime/DerivedComposed.cs | 12 +- src/WinRT.Runtime/Directory.Build.targets | 1 + src/WinRT.Runtime/EventRegistrationToken.cs | 9 +- src/WinRT.Runtime/ExceptionHelpers.cs | 56 +- src/WinRT.Runtime/FundamentalMarshalers.cs | 2 - src/WinRT.Runtime/GuidGenerator.cs | 15 +- src/WinRT.Runtime/IInspectable.cs | 26 +- src/WinRT.Runtime/IInspectable.net5.cs | 19 +- src/WinRT.Runtime/IWinRTObject.net5.cs | 9 +- .../Interop/ExceptionErrorInfo.cs | 20 +- .../Interop/IActivationFactory.cs | 15 +- .../Interop/IAgileReference.net5.cs | 6 +- .../Interop/IAgileReference.netstandard2.0.cs | 14 +- src/WinRT.Runtime/Interop/IMarshal.cs | 16 +- .../Interop/IWeakReferenceSource.net5.cs | 18 +- .../IWeakReferenceSource.netstandard2.0.cs | 14 +- .../Interop/StandardDelegates.cs | 16 +- src/WinRT.Runtime/Marshalers.cs | 185 +++--- src/WinRT.Runtime/Module.cs | 2 +- src/WinRT.Runtime/MonoSupport.cs | 2 - src/WinRT.Runtime/ObjectReference.cs | 591 +++++++++--------- src/WinRT.Runtime/Projections.cs | 11 +- .../Projections/Bindable.netstandard2.0.cs | 27 +- .../Projections/DataErrorsChangedEventArgs.cs | 9 +- src/WinRT.Runtime/Projections/EventHandler.cs | 113 ++-- src/WinRT.Runtime/Projections/Geometry.cs | 66 +- .../Projections/ICommand.net5.cs | 14 +- .../Projections/ICommand.netstandard2.0.cs | 14 +- .../Projections/IDictionary.netstandard2.0.cs | 17 +- .../Projections/IDisposable.netstandard2.0.cs | 7 +- .../Projections/IEnumerable.net5.cs | 9 +- .../Projections/IEnumerable.netstandard2.0.cs | 36 +- .../Projections/IList.netstandard2.0.cs | 18 +- .../INotifyCollectionChanged.net5.cs | 9 +- ...INotifyCollectionChanged.netstandard2.0.cs | 7 +- .../Projections/INotifyDataErrorInfo.net5.cs | 7 +- .../INotifyDataErrorInfo.netstandard2.0.cs | 21 +- .../INotifyPropertyChanged.netstandard2.0.cs | 7 +- .../Projections/IPropertyValue.net5.cs | 6 +- .../IPropertyValue.netstandard2.0.cs | 6 +- .../IReadOnlyDictionary.netstandard2.0.cs | 18 +- .../IReadOnlyList.netstandard2.0.cs | 17 +- .../Projections/IReferenceArray.net5.cs | 2 +- .../IReferenceArray.netstandard2.0.cs | 2 +- .../IServiceProvider.netstandard2.0.cs | 7 +- src/WinRT.Runtime/Projections/IStringable.cs | 6 +- src/WinRT.Runtime/Projections/KeyValuePair.cs | 9 +- .../NotifyCollectionChangedEventArgs.cs | 9 +- .../NotifyCollectionChangedEventHandler.cs | 89 +-- src/WinRT.Runtime/Projections/Nullable.cs | 9 +- .../Projections/PropertyChangedEventArgs.cs | 9 +- .../PropertyChangedEventHandler.cs | 89 +-- src/WinRT.Runtime/Projections/Uri.cs | 9 +- .../SingleInterfaceOptimizedObject.net5.cs | 13 +- src/WinRT.Runtime/TypeExtensions.cs | 64 +- src/WinRT.Runtime/TypeNameSupport.cs | 34 +- .../WeakReference.netstandard2.0.cs | 12 +- 69 files changed, 1234 insertions(+), 810 deletions(-) diff --git a/src/Authoring/WinRT.Host.Shim/Module.cs b/src/Authoring/WinRT.Host.Shim/Module.cs index 532d7c008..ef439aad3 100644 --- a/src/Authoring/WinRT.Host.Shim/Module.cs +++ b/src/Authoring/WinRT.Host.Shim/Module.cs @@ -5,7 +5,7 @@ using System.Collections.Concurrent; using System.Reflection; -#if !NETSTANDARD2_0 +#if NET using System.Runtime.Loader; [assembly: global::System.Runtime.Versioning.SupportedOSPlatform("Windows")] #endif @@ -56,7 +56,7 @@ public static unsafe int GetActivationFactory(IntPtr hstrTargetAssembly, IntPtr } } -#if NETSTANDARD2_0 +#if !NET private static class ActivationLoader { public static Assembly LoadAssembly(string targetAssembly) => Assembly.LoadFrom(targetAssembly); @@ -64,7 +64,7 @@ private static class ActivationLoader #else private class ActivationLoader : AssemblyLoadContext { - private static readonly ConcurrentDictionary ALCMapping = new ConcurrentDictionary(StringComparer.Ordinal); + private static readonly ConcurrentDictionary ALCMapping = new ConcurrentDictionary(); private AssemblyDependencyResolver _resolver; public static Assembly LoadAssembly(string targetAssembly) @@ -79,7 +79,7 @@ private ActivationLoader(string path) AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext assemblyLoadContext, AssemblyName assemblyName) => { // Consolidate all WinRT.Runtime loads to the default ALC, or failing that, the first shim ALC - if (string.CompareOrdinal(assemblyName.Name, "WinRT.Runtime") == 0) + if (assemblyName.Name == "WinRT.Runtime") { string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); if (assemblyPath != null) @@ -93,7 +93,7 @@ private ActivationLoader(string path) protected override Assembly Load(AssemblyName assemblyName) { - if (string.CompareOrdinal(assemblyName.Name, "WinRT.Runtime") != 0) + if (assemblyName.Name != "WinRT.Runtime") { string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); if (assemblyPath != null) diff --git a/src/Projections/Test/Module.cs b/src/Projections/Test/Module.cs index c7da65e22..636144eed 100644 --- a/src/Projections/Test/Module.cs +++ b/src/Projections/Test/Module.cs @@ -1,3 +1,3 @@ -#if !NETSTANDARD2_0 +#if NET [assembly: global::System.Runtime.Versioning.SupportedOSPlatform("Windows")] #endif diff --git a/src/Projections/TestHost.ProbeByClass/Module.cs b/src/Projections/TestHost.ProbeByClass/Module.cs index c7da65e22..636144eed 100644 --- a/src/Projections/TestHost.ProbeByClass/Module.cs +++ b/src/Projections/TestHost.ProbeByClass/Module.cs @@ -1,3 +1,3 @@ -#if !NETSTANDARD2_0 +#if NET [assembly: global::System.Runtime.Versioning.SupportedOSPlatform("Windows")] #endif diff --git a/src/Projections/Windows/Module.cs b/src/Projections/Windows/Module.cs index c7da65e22..636144eed 100644 --- a/src/Projections/Windows/Module.cs +++ b/src/Projections/Windows/Module.cs @@ -1,3 +1,3 @@ -#if !NETSTANDARD2_0 +#if NET [assembly: global::System.Runtime.Versioning.SupportedOSPlatform("Windows")] #endif diff --git a/src/Tests/AuthoringTest/Module.cs b/src/Tests/AuthoringTest/Module.cs index c7da65e22..636144eed 100644 --- a/src/Tests/AuthoringTest/Module.cs +++ b/src/Tests/AuthoringTest/Module.cs @@ -1,3 +1,3 @@ -#if !NETSTANDARD2_0 +#if NET [assembly: global::System.Runtime.Versioning.SupportedOSPlatform("Windows")] #endif diff --git a/src/WinRT.Runtime/AgileReference.cs b/src/WinRT.Runtime/AgileReference.cs index d910470b3..6b2831e85 100644 --- a/src/WinRT.Runtime/AgileReference.cs +++ b/src/WinRT.Runtime/AgileReference.cs @@ -4,7 +4,12 @@ namespace WinRT { - public class AgileReference : IDisposable +#if EMBED + internal +#else + public +#endif + class AgileReference : IDisposable { private readonly static Guid CLSID_StdGlobalInterfaceTable = Guid.Parse("00000323-0000-0000-c000-000000000046"); private readonly static Lazy Git = new Lazy(() => GetGitTable()); @@ -12,7 +17,12 @@ public class AgileReference : IDisposable private readonly IntPtr _cookie; private bool disposed; - public unsafe AgileReference(IObjectReference instance) + #if EMBED + internal +#else + public +#endif + unsafe AgileReference(IObjectReference instance) { if(instance?.ThisPtr == null) { @@ -44,7 +54,12 @@ public unsafe AgileReference(IObjectReference instance) } } - public IObjectReference Get() => _cookie == IntPtr.Zero ? _agileReference?.Resolve(typeof(IUnknownVftbl).GUID) : Git.Value?.GetInterfaceFromGlobal(_cookie, typeof(IUnknownVftbl).GUID); +#if EMBED + internal +#else + public +#endif + IObjectReference Get() => _cookie == IntPtr.Zero ? _agileReference?.Resolve(typeof(IUnknownVftbl).GUID) : Git.Value?.GetInterfaceFromGlobal(_cookie, typeof(IUnknownVftbl).GUID); protected virtual void Dispose(bool disposing) { @@ -99,15 +114,31 @@ public void Dispose() } } - public sealed class AgileReference : AgileReference +#if EMBED + internal +#else + public +#endif + sealed class AgileReference : AgileReference where T : class { - public unsafe AgileReference(IObjectReference instance) + +#if EMBED + internal +#else + public +#endif + unsafe AgileReference(IObjectReference instance) : base(instance) { } - public new T Get() +#if EMBED + internal +#else + public +#endif + new T Get() { using var objRef = base.Get(); return ComWrappersSupport.CreateRcwForComObject(objRef?.ThisPtr ?? IntPtr.Zero); diff --git a/src/WinRT.Runtime/Attributes.cs b/src/WinRT.Runtime/Attributes.cs index 9b6cc3160..8a59798a5 100644 --- a/src/WinRT.Runtime/Attributes.cs +++ b/src/WinRT.Runtime/Attributes.cs @@ -1,13 +1,16 @@ using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Text; namespace WinRT { [EditorBrowsable(EditorBrowsableState.Never)] - [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] - public sealed class ProjectedRuntimeClassAttribute : Attribute + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] +#if EMBED + internal +#else + public +#endif + sealed class ProjectedRuntimeClassAttribute : Attribute { public ProjectedRuntimeClassAttribute(string defaultInterfaceProp) { @@ -25,7 +28,12 @@ public ProjectedRuntimeClassAttribute(Type defaultInterface) [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] - public sealed class ObjectReferenceWrapperAttribute : Attribute +#if EMBED + internal +#else + public +#endif + sealed class ObjectReferenceWrapperAttribute : Attribute { public ObjectReferenceWrapperAttribute(string objectReferenceField) { @@ -40,7 +48,12 @@ public ObjectReferenceWrapperAttribute(string objectReferenceField) /// [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate | AttributeTargets.Struct | AttributeTargets.Enum, Inherited = false, AllowMultiple = false)] - public sealed class WindowsRuntimeTypeAttribute : Attribute +#if EMBED + internal +#else + public +#endif + sealed class WindowsRuntimeTypeAttribute : Attribute { public WindowsRuntimeTypeAttribute(string sourceMetadata = null) { diff --git a/src/WinRT.Runtime/CastExtensions.cs b/src/WinRT.Runtime/CastExtensions.cs index ade5fa4a6..55faaebc5 100644 --- a/src/WinRT.Runtime/CastExtensions.cs +++ b/src/WinRT.Runtime/CastExtensions.cs @@ -1,14 +1,15 @@ using System; -using System.Collections.Generic; using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; using WinRT.Interop; namespace WinRT { - public static class CastExtensions +#if EMBED + internal +#else + public +#endif + static class CastExtensions { /// /// Cast a WinRT object to an interface type it implements in its implementation @@ -22,7 +23,12 @@ public static class CastExtensions /// Otherwise, creates a new wrapper of the underlying WinRT object that implements . /// /// Thrown if the runtime type of is not a projected type (if the object is a managed object). - public static TInterface As(this object value) +#if EMBED + internal +#else + public +#endif + static TInterface As(this object value) { if (typeof(TInterface) == typeof(object)) { @@ -57,7 +63,12 @@ public static TInterface As(this object value) /// Otherwise, returns null. /// /// Thrown if the runtime type of is not a projected type. - public static AgileReference AsAgile(this T value) where T : class +#if EMBED + internal +#else + public +#endif + static AgileReference AsAgile(this T value) where T : class { if(value == null) { @@ -103,7 +114,7 @@ private static IObjectReference GetRefForObject(object value) private static bool TryGetComposedRefForQI(object value, out IObjectReference objRef) { -#if NETSTANDARD2_0 +#if !NET var getReferenceMethod = value.GetType().GetMethod("GetDefaultReference", BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod(typeof(IUnknownVftbl)); if (getReferenceMethod is null) { diff --git a/src/WinRT.Runtime/ComWrappersSupport.cs b/src/WinRT.Runtime/ComWrappersSupport.cs index e1f59c0e6..dff5f564b 100644 --- a/src/WinRT.Runtime/ComWrappersSupport.cs +++ b/src/WinRT.Runtime/ComWrappersSupport.cs @@ -1,21 +1,15 @@ +using ABI.Microsoft.UI.Xaml.Data; +using ABI.Windows.Foundation; using System; -using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; +using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Numerics; -using System.Security.Cryptography; -using System.Text; -using System.Threading; -using System.Linq.Expressions; using WinRT.Interop; -using ABI.Windows.Foundation; -using ABI.Microsoft.UI.Xaml.Data; -#if !NETSTANDARD2_0 +#if NET using ComInterfaceEntry = System.Runtime.InteropServices.ComWrappers.ComInterfaceEntry; #endif @@ -23,10 +17,15 @@ #pragma warning disable 0649 // Field 'xxx' is never assigned to, and will always have its default value namespace WinRT -{ - public static partial class ComWrappersSupport +{ +#if EMBED + internal +#else + public +#endif + static partial class ComWrappersSupport { - private readonly static ConcurrentDictionary> TypedObjectFactoryCache = new ConcurrentDictionary>(StringComparer.Ordinal); + private readonly static ConcurrentDictionary> TypedObjectFactoryCache = new ConcurrentDictionary>(); private readonly static ConditionalWeakTable CCWTable = new ConditionalWeakTable(); public static TReturn MarshalDelegateInvoke(IntPtr thisPtr, Func invoke) @@ -244,7 +243,7 @@ internal static (InspectableInfo inspectableInfo, List interf iids[i] = interfaceTableEntries[i].IID; } - if (type.FullName.StartsWith("ABI.", StringComparison.Ordinal)) + if (type.FullName.StartsWith("ABI.")) { type = Projections.FindCustomPublicTypeForAbiType(type) ?? type.Assembly.GetType(type.FullName.Substring("ABI.".Length)) ?? type; } @@ -261,7 +260,7 @@ private static bool IsNullableT(Type implementationType) private static bool IsIReferenceArray(Type implementationType) { - return implementationType.FullName.StartsWith("Windows.Foundation.IReferenceArray`1", StringComparison.Ordinal); + return implementationType.FullName.StartsWith("Windows.Foundation.IReferenceArray`1"); } private static Func CreateKeyValuePairFactory(Type type) @@ -317,17 +316,16 @@ private static Func CreateReferenceCachingFactory(Func CreateTypedRcwFactory(string runtimeClassName) { // If runtime class name is empty or "Object", then just use IInspectable. - if (string.IsNullOrEmpty(runtimeClassName) || - string.CompareOrdinal(runtimeClassName, "Object") == 0) + if (string.IsNullOrEmpty(runtimeClassName) || runtimeClassName == "Object") { return (IInspectable obj) => obj; } // PropertySet and ValueSet can return IReference but Nullable is illegal - if (string.CompareOrdinal(runtimeClassName, "Windows.Foundation.IReference`1") == 0) + if (runtimeClassName == "Windows.Foundation.IReference`1") { return CreateReferenceCachingFactory((IInspectable obj) => new ABI.System.Nullable(obj.ObjRef)); } - else if (string.CompareOrdinal(runtimeClassName, "Windows.Foundation.IReference`1") == 0) + else if (runtimeClassName == "Windows.Foundation.IReference`1") { return CreateReferenceCachingFactory((IInspectable obj) => new ABI.System.Nullable(obj.ObjRef)); } diff --git a/src/WinRT.Runtime/ComWrappersSupport.net5.cs b/src/WinRT.Runtime/ComWrappersSupport.net5.cs index aa684bc9b..953a69345 100644 --- a/src/WinRT.Runtime/ComWrappersSupport.net5.cs +++ b/src/WinRT.Runtime/ComWrappersSupport.net5.cs @@ -11,7 +11,12 @@ namespace WinRT { - public static partial class ComWrappersSupport +#if EMBED + internal +#else + public +#endif + static partial class ComWrappersSupport { // Instance field and property for Singleton pattern: ComWrappers `set` method should be idempotent private static DefaultComWrappers _instance; @@ -43,7 +48,9 @@ private static ComWrappers ComWrappers if (_comWrappers is null) { var comWrappersToSet = DefaultComWrappersInstance; +#if !EMBED ComWrappers.RegisterForTrackerSupport(comWrappersToSet); +#endif _comWrappers = comWrappersToSet; } } @@ -59,7 +66,9 @@ private static ComWrappers ComWrappers return; } var comWrappersToSet = value ?? DefaultComWrappersInstance; +#if !EMBED ComWrappers.RegisterForTrackerSupport(comWrappersToSet); +#endif _comWrappers = comWrappersToSet; } } @@ -205,8 +214,12 @@ private static Func CreateFactoryForImplementationType(str parms).Compile(); } } - - public class ComWrappersHelper +#if EMBED + internal +#else + public +#endif + class ComWrappersHelper { public unsafe static void Init( bool isAggregation, @@ -354,8 +367,12 @@ public unsafe static void Init(IObjectReference objRef, bool addRefFromTrackerSo } } } - - public class DefaultComWrappers : ComWrappers +#if EMBED + internal +#else + public +#endif + class DefaultComWrappers : ComWrappers { private static readonly ConditionalWeakTable TypeVtableEntryTable = new ConditionalWeakTable(); public static unsafe IUnknownVftbl IUnknownVftbl => Unsafe.AsRef(IUnknownVftblPtr.ToPointer()); diff --git a/src/WinRT.Runtime/ComWrappersSupport.netstandard2.0.cs b/src/WinRT.Runtime/ComWrappersSupport.netstandard2.0.cs index d85cd79bf..808af8244 100644 --- a/src/WinRT.Runtime/ComWrappersSupport.netstandard2.0.cs +++ b/src/WinRT.Runtime/ComWrappersSupport.netstandard2.0.cs @@ -10,7 +10,12 @@ namespace WinRT { - public static partial class ComWrappersSupport +#if EMBED + internal +#else + public +#endif + static partial class ComWrappersSupport { private static ConditionalWeakTable ComWrapperCache = new ConditionalWeakTable(); @@ -268,12 +273,18 @@ private static Func CreateFactoryForImplementationType(str } +#if EMBED + internal +#endif struct ComInterfaceEntry { public IntPtr Vtable; public Guid IID; } +#if EMBED + internal +#endif struct UnmanagedObject { public IntPtr _vftblPtr; diff --git a/src/WinRT.Runtime/Context.cs b/src/WinRT.Runtime/Context.cs index 17c89a794..a5d895e5a 100644 --- a/src/WinRT.Runtime/Context.cs +++ b/src/WinRT.Runtime/Context.cs @@ -4,6 +4,9 @@ namespace WinRT { +#if EMBED + internal +#endif static class Context { [DllImport("api-ms-win-core-com-l1-1-0.dll")] @@ -60,7 +63,7 @@ public unsafe static void CallInContext(IntPtr contextCallbackPtr, IntPtr contex public static void DisposeContextCallback(IntPtr contextCallbackPtr) { - MarshalInspectable.DisposeAbi(contextCallbackPtr); + using var contextcallback = ObjectReference.Attach(ref contextCallbackPtr); } } } diff --git a/src/WinRT.Runtime/DerivedComposed.cs b/src/WinRT.Runtime/DerivedComposed.cs index ae8cc2e52..70272b680 100644 --- a/src/WinRT.Runtime/DerivedComposed.cs +++ b/src/WinRT.Runtime/DerivedComposed.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; +using System.ComponentModel; namespace WinRT { @@ -10,7 +7,12 @@ namespace WinRT /// as a base class of another composable object. /// [EditorBrowsable(EditorBrowsableState.Never)] - public class DerivedComposed +#if EMBED + internal +#else + public +#endif + class DerivedComposed { public static readonly DerivedComposed Instance = new DerivedComposed(); diff --git a/src/WinRT.Runtime/Directory.Build.targets b/src/WinRT.Runtime/Directory.Build.targets index c4c20d0a7..5e547527b 100644 --- a/src/WinRT.Runtime/Directory.Build.targets +++ b/src/WinRT.Runtime/Directory.Build.targets @@ -8,4 +8,5 @@ Copyright (C) Microsoft Corporation. All rights reserved. + \ No newline at end of file diff --git a/src/WinRT.Runtime/EventRegistrationToken.cs b/src/WinRT.Runtime/EventRegistrationToken.cs index a0e50a37f..304250261 100644 --- a/src/WinRT.Runtime/EventRegistrationToken.cs +++ b/src/WinRT.Runtime/EventRegistrationToken.cs @@ -1,10 +1,13 @@ using System; -using System.Collections.Generic; -using System.Text; namespace WinRT { - public struct EventRegistrationToken : IEquatable +#if EMBED + internal +#else + public +#endif + struct EventRegistrationToken : IEquatable { public long Value; diff --git a/src/WinRT.Runtime/ExceptionHelpers.cs b/src/WinRT.Runtime/ExceptionHelpers.cs index 395373253..8410fa023 100644 --- a/src/WinRT.Runtime/ExceptionHelpers.cs +++ b/src/WinRT.Runtime/ExceptionHelpers.cs @@ -6,7 +6,12 @@ namespace WinRT { - public static class ExceptionHelpers +#if EMBED + internal +#else + public +#endif + static class ExceptionHelpers { private const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622); private const int RO_E_CLOSED = unchecked((int)0x80000013); @@ -364,9 +369,14 @@ public static Exception AttachRestrictedErrorInfo(Exception e) return e; } - } - - public static class ExceptionExtensions + } + +#if EMBED + internal +#else + public +#endif + static class ExceptionExtensions { public static void SetHResult(this Exception ex, int value) { @@ -420,8 +430,14 @@ namespace Microsoft.UI.Xaml using System.Runtime.Serialization; namespace Automation { - [Serializable] - public class ElementNotAvailableException : Exception + [Serializable] +#if EMBED + internal +#else + public +#endif + + class ElementNotAvailableException : Exception { public ElementNotAvailableException() : base("The element is not available.") @@ -445,9 +461,14 @@ protected ElementNotAvailableException(SerializationInfo serializationInfo, Stre : base(serializationInfo, streamingContext) { } - } - - public class ElementNotEnabledException : Exception + } + +#if EMBED + internal +#else + public +#endif + class ElementNotEnabledException : Exception { public ElementNotEnabledException() : base("The element is not enabled.") @@ -470,7 +491,13 @@ public ElementNotEnabledException(string message, Exception innerException) } namespace Markup { - public class XamlParseException : Exception + +#if EMBED + internal +#else + public +#endif + class XamlParseException : Exception { public XamlParseException() : base("XAML parsing failed.") @@ -491,8 +518,13 @@ public XamlParseException(string message, Exception innerException) } } } - [Serializable] - public class LayoutCycleException : Exception + [Serializable] +#if EMBED + internal +#else + public +#endif + class LayoutCycleException : Exception { public LayoutCycleException() : base("A cycle occurred while laying out the GUI.") diff --git a/src/WinRT.Runtime/FundamentalMarshalers.cs b/src/WinRT.Runtime/FundamentalMarshalers.cs index 5ab5e0944..3b93c06ee 100644 --- a/src/WinRT.Runtime/FundamentalMarshalers.cs +++ b/src/WinRT.Runtime/FundamentalMarshalers.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace ABI.System { diff --git a/src/WinRT.Runtime/GuidGenerator.cs b/src/WinRT.Runtime/GuidGenerator.cs index 3fa0063bc..abdff49c4 100644 --- a/src/WinRT.Runtime/GuidGenerator.cs +++ b/src/WinRT.Runtime/GuidGenerator.cs @@ -6,7 +6,12 @@ namespace WinRT { - public static class GuidGenerator +#if EMBED + internal +#else + public +#endif + static class GuidGenerator { public static Guid GetGUID(Type type) { @@ -33,8 +38,8 @@ public static string GetSignature(Type type) { return (string)sigMethod.Invoke(null, new Type[] { }); } - } - + } + type = type.IsInterface ? (type.GetAuthoringMetadataType() ?? type) : type; if (type == typeof(object)) { @@ -121,7 +126,7 @@ private static Guid encode_guid(Span data) // encode rfc clock/reserved field data[8] = (byte)((data[8] & 0x3f) | 0x80); } -#if NETSTANDARD2_0 +#if !NET return new Guid(data.Slice(0, 16).ToArray()); #else return new Guid(data[0..16]); @@ -137,7 +142,7 @@ public static Guid CreateIID(Type type) { return new Guid(sig); } -#if NETSTANDARD2_0 +#if !NET var data = wrt_pinterface_namespace.ToByteArray().Concat(UTF8Encoding.UTF8.GetBytes(sig)).ToArray(); #else var maxBytes = UTF8Encoding.UTF8.GetMaxByteCount(sig.Length); diff --git a/src/WinRT.Runtime/IInspectable.cs b/src/WinRT.Runtime/IInspectable.cs index fbcadf9ef..eef1e6554 100644 --- a/src/WinRT.Runtime/IInspectable.cs +++ b/src/WinRT.Runtime/IInspectable.cs @@ -1,12 +1,15 @@ using System; -using System.Collections.Generic; using System.Runtime.InteropServices; -using System.Text; using WinRT.Interop; namespace WinRT { - public enum TrustLevel +#if EMBED + internal +#else + public +#endif + enum TrustLevel { BaseTrust = 0, PartialTrust = BaseTrust + 1, @@ -16,7 +19,12 @@ public enum TrustLevel // IInspectable [ObjectReferenceWrapper(nameof(_obj))] [Guid("AF86E2E0-B12D-4c6a-9C5A-D7AA65101E90")] - public partial class IInspectable +#if EMBED + internal +#else + public +#endif + partial class IInspectable { [Guid("AF86E2E0-B12D-4c6a-9C5A-D7AA65101E90")] public unsafe struct Vftbl @@ -34,7 +42,7 @@ public unsafe struct Vftbl public static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 +#if !NET private static readonly Delegate[] DelegateCache = new Delegate[3]; private delegate int _GetIidsDelegate(IntPtr pThis, int* iidCount, IntPtr* iids); private delegate int _GetRuntimeClassNameDelegate(IntPtr pThis, IntPtr* className); @@ -46,7 +54,7 @@ static Vftbl() AbiToProjectionVftable = new Vftbl { IUnknownVftbl = IUnknownVftbl.AbiToProjectionVftbl, -#if NETSTANDARD2_0 +#if !NET _GetIids = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new _GetIidsDelegate(Do_Abi_GetIids)), _GetRuntimeClassName = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new _GetRuntimeClassNameDelegate(Do_Abi_GetRuntimeClassName)), _GetTrustLevel = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[2] = new _GetTrustLevelDelegate(Do_Abi_GetTrustLevel)) @@ -60,7 +68,7 @@ static Vftbl() Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false); } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private static int Do_Abi_GetIids(IntPtr pThis, int* iidCount, IntPtr* iids) @@ -78,7 +86,7 @@ private static int Do_Abi_GetIids(IntPtr pThis, int* iidCount, IntPtr* iids) return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private unsafe static int Do_Abi_GetRuntimeClassName(IntPtr pThis, IntPtr* className) @@ -96,7 +104,7 @@ private unsafe static int Do_Abi_GetRuntimeClassName(IntPtr pThis, IntPtr* class return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private static int Do_Abi_GetTrustLevel(IntPtr pThis, TrustLevel* trustLevel) diff --git a/src/WinRT.Runtime/IInspectable.net5.cs b/src/WinRT.Runtime/IInspectable.net5.cs index ca652a83f..557a189c0 100644 --- a/src/WinRT.Runtime/IInspectable.net5.cs +++ b/src/WinRT.Runtime/IInspectable.net5.cs @@ -2,16 +2,19 @@ using System.Collections.Concurrent; namespace WinRT -{ - public partial class IInspectable : IWinRTObject +{ +#if EMBED + internal +#else + public +#endif + partial class IInspectable : IWinRTObject { IObjectReference IWinRTObject.NativeObject => _obj; - bool IWinRTObject.HasUnwrappableNativeObject => true; - - private Lazy> _lazyQueryInterfaceCache = new(); - ConcurrentDictionary IWinRTObject.QueryInterfaceCache => _lazyQueryInterfaceCache.Value; - private Lazy> _lazyAdditionalTypeData = new(); - ConcurrentDictionary IWinRTObject.AdditionalTypeData => _lazyAdditionalTypeData.Value; + bool IWinRTObject.HasUnwrappableNativeObject => true; + + ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); + ConcurrentDictionary IWinRTObject.AdditionalTypeData { get; } = new(); } } diff --git a/src/WinRT.Runtime/IWinRTObject.net5.cs b/src/WinRT.Runtime/IWinRTObject.net5.cs index 59b298b33..3da2863fb 100644 --- a/src/WinRT.Runtime/IWinRTObject.net5.cs +++ b/src/WinRT.Runtime/IWinRTObject.net5.cs @@ -5,8 +5,13 @@ using WinRT.Interop; namespace WinRT -{ - public interface IWinRTObject : IDynamicInterfaceCastable +{ +#if EMBED + internal +#else + public +#endif + interface IWinRTObject : IDynamicInterfaceCastable { bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented) { diff --git a/src/WinRT.Runtime/Interop/ExceptionErrorInfo.cs b/src/WinRT.Runtime/Interop/ExceptionErrorInfo.cs index 49eb52bd1..81caa2ff1 100644 --- a/src/WinRT.Runtime/Interop/ExceptionErrorInfo.cs +++ b/src/WinRT.Runtime/Interop/ExceptionErrorInfo.cs @@ -107,7 +107,7 @@ public struct Vftbl private static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 +#if !NET public delegate int GetGuidDelegate(IntPtr thisPtr, Guid* guid); public delegate int GetBstrDelegate(IntPtr thisPtr, IntPtr* bstr); private static readonly Delegate[] DelegateCache = new Delegate[5]; @@ -118,7 +118,7 @@ static unsafe Vftbl() AbiToProjectionVftable = new Vftbl { IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, -#if NETSTANDARD2_0 +#if !NET _GetGuid_0 = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new GetGuidDelegate(Do_Abi_GetGuid_0)).ToPointer(), _GetSource_1 = Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new GetBstrDelegate(Do_Abi_GetSource_1)).ToPointer(), _GetDescription_2 = Marshal.GetFunctionPointerForDelegate(DelegateCache[2] = new GetBstrDelegate(Do_Abi_GetDescription_2)).ToPointer(), @@ -137,7 +137,7 @@ static unsafe Vftbl() AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private static int Do_Abi_GetGuid_0(IntPtr thisPtr, Guid* guid) @@ -154,7 +154,7 @@ private static int Do_Abi_GetGuid_0(IntPtr thisPtr, Guid* guid) return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private static int Do_Abi_GetSource_1(IntPtr thisPtr, IntPtr* source) @@ -175,7 +175,7 @@ private static int Do_Abi_GetSource_1(IntPtr thisPtr, IntPtr* source) return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private static int Do_Abi_GetDescription_2(IntPtr thisPtr, IntPtr* description) @@ -196,7 +196,7 @@ private static int Do_Abi_GetDescription_2(IntPtr thisPtr, IntPtr* description) return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private static int Do_Abi_GetHelpFile_3(IntPtr thisPtr, IntPtr* helpFile) @@ -217,7 +217,7 @@ private static int Do_Abi_GetHelpFile_3(IntPtr thisPtr, IntPtr* helpFile) return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private static int Do_Abi_GetHelpFileContent_4(IntPtr thisPtr, IntPtr* helpFileContent) @@ -373,7 +373,7 @@ public struct Vftbl private static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 +#if !NET public delegate int _InterfaceSupportsErrorInfo(IntPtr thisPtr, Guid* riid); private static readonly _InterfaceSupportsErrorInfo DelegateCache; #endif @@ -382,7 +382,7 @@ static unsafe Vftbl() AbiToProjectionVftable = new Vftbl { IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, -#if NETSTANDARD2_0 +#if !NET _InterfaceSupportsErrorInfo_0 = Marshal.GetFunctionPointerForDelegate(DelegateCache = Do_Abi_InterfaceSupportsErrorInfo_0).ToPointer() #else _InterfaceSupportsErrorInfo_0 = (delegate* unmanaged)&Do_Abi_InterfaceSupportsErrorInfo_0 @@ -392,7 +392,7 @@ static unsafe Vftbl() Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private static int Do_Abi_InterfaceSupportsErrorInfo_0(IntPtr thisPtr, Guid* guid) diff --git a/src/WinRT.Runtime/Interop/IActivationFactory.cs b/src/WinRT.Runtime/Interop/IActivationFactory.cs index 0487e2ef8..d9c674022 100644 --- a/src/WinRT.Runtime/Interop/IActivationFactory.cs +++ b/src/WinRT.Runtime/Interop/IActivationFactory.cs @@ -19,13 +19,18 @@ namespace ABI.WinRT.Interop { [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] [Guid("00000035-0000-0000-C000-000000000046")] - public unsafe class IActivationFactory : global::WinRT.Interop.IActivationFactory +#if EMBED + internal +#else + public +#endif + unsafe class IActivationFactory : global::WinRT.Interop.IActivationFactory { [Guid("00000035-0000-0000-C000-000000000046")] public struct Vftbl { internal IInspectable.Vftbl IInspectableVftbl; -#if NETSTANDARD2_0 +#if !NET private delegate int ActivateInstance_Delegate(IntPtr thisPtr, IntPtr* pobj); private void* _ActivateInstance_0; public delegate* unmanaged[Stdcall] ActivateInstance_0 { get => (delegate* unmanaged[Stdcall])_ActivateInstance_0; set => _ActivateInstance_0 = value; } @@ -34,7 +39,7 @@ public struct Vftbl #endif public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 +#if !NET private static readonly Delegate[] DelegateCache = new Delegate[1]; #endif static unsafe Vftbl() @@ -43,7 +48,7 @@ static unsafe Vftbl() (*(Vftbl*)AbiToProjectionVftablePtr) = new Vftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 +#if !NET _ActivateInstance_0 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ActivateInstance_Delegate(Do_Abi_ActivateInstance_0)) #else ActivateInstance_0 = &Do_Abi_ActivateInstance_0 @@ -51,7 +56,7 @@ static unsafe Vftbl() }; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new [] { typeof(CallConvStdcall) })] #endif private static unsafe int Do_Abi_ActivateInstance_0(IntPtr thisPtr, IntPtr* result) diff --git a/src/WinRT.Runtime/Interop/IAgileReference.net5.cs b/src/WinRT.Runtime/Interop/IAgileReference.net5.cs index 7d44e59b0..63f699b68 100644 --- a/src/WinRT.Runtime/Interop/IAgileReference.net5.cs +++ b/src/WinRT.Runtime/Interop/IAgileReference.net5.cs @@ -48,7 +48,7 @@ public struct Vftbl public static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 +#if !NET public delegate int ResolveDelegate(IntPtr thisPtr, Guid* riid, IntPtr* objectReference); private static readonly Delegate[] DelegateCache = new Delegate[1]; #endif @@ -57,7 +57,7 @@ static Vftbl() AbiToProjectionVftable = new Vftbl { IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, -#if NETSTANDARD2_0 +#if !NET _Resolve = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ResolveDelegate(Do_Abi_Resolve)).ToPointer(), #else _Resolve = (delegate* unmanaged)&Do_Abi_Resolve @@ -67,7 +67,7 @@ static Vftbl() Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false); } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private static int Do_Abi_Resolve(IntPtr thisPtr, Guid* riid, IntPtr* objectReference) diff --git a/src/WinRT.Runtime/Interop/IAgileReference.netstandard2.0.cs b/src/WinRT.Runtime/Interop/IAgileReference.netstandard2.0.cs index e7fd6c92d..7eb48561e 100644 --- a/src/WinRT.Runtime/Interop/IAgileReference.netstandard2.0.cs +++ b/src/WinRT.Runtime/Interop/IAgileReference.netstandard2.0.cs @@ -14,7 +14,12 @@ internal interface IAgileReference [WindowsRuntimeType] [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] - public interface IAgileObject +#if EMBED + internal +#else + public +#endif + interface IAgileObject { } @@ -112,7 +117,12 @@ public IObjectReference Resolve(Guid riid) } [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] - public class IAgileObject : global::WinRT.Interop.IAgileObject +#if EMBED + internal +#else + public +#endif + class IAgileObject : global::WinRT.Interop.IAgileObject { [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] public struct Vftbl diff --git a/src/WinRT.Runtime/Interop/IMarshal.cs b/src/WinRT.Runtime/Interop/IMarshal.cs index ff0054bfe..157ca7baf 100644 --- a/src/WinRT.Runtime/Interop/IMarshal.cs +++ b/src/WinRT.Runtime/Interop/IMarshal.cs @@ -44,7 +44,7 @@ public unsafe struct Vftbl { internal global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; -#if NETSTANDARD2_0 +#if !NET private void* _GetUnmarshalClass_0; public delegate* unmanaged[Stdcall] GetUnmarshalClass_0 { get => (delegate* unmanaged[Stdcall])_GetUnmarshalClass_0; set => _GetUnmarshalClass_0 = value; } private void* _GetMarshalSizeMax_1; @@ -73,7 +73,7 @@ public unsafe struct Vftbl static Vftbl() { -#if NETSTANDARD2_0 +#if !NET AbiToProjectionVftable = new Vftbl { IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, @@ -133,7 +133,7 @@ internal static Guid GetInProcFreeThreadedMarshalerIID() return iid_unmarshalClass; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int Do_Abi_GetUnmarshalClass_0(IntPtr thisPtr, Guid* riid, IntPtr pv, global::WinRT.Interop.MSHCTX dwDestContext, IntPtr pvDestContext, global::WinRT.Interop.MSHLFLAGS mshlFlags, Guid* pCid) @@ -151,7 +151,7 @@ private static int Do_Abi_GetUnmarshalClass_0(IntPtr thisPtr, Guid* riid, IntPtr return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int Do_Abi_GetMarshalSizeMax_1(IntPtr thisPtr, Guid* riid, IntPtr pv, global::WinRT.Interop.MSHCTX dwDestContext, IntPtr pvDestContext, global::WinRT.Interop.MSHLFLAGS mshlflags, uint* pSize) @@ -169,7 +169,7 @@ private static int Do_Abi_GetMarshalSizeMax_1(IntPtr thisPtr, Guid* riid, IntPtr return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int Do_Abi_MarshalInterface_2(IntPtr thisPtr, IntPtr pStm, Guid* riid, IntPtr pv, global::WinRT.Interop.MSHCTX dwDestContext, IntPtr pvDestContext, global::WinRT.Interop.MSHLFLAGS mshlflags) @@ -186,7 +186,7 @@ private static int Do_Abi_MarshalInterface_2(IntPtr thisPtr, IntPtr pStm, Guid* return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int Do_Abi_UnmarshalInterface_3(IntPtr thisPtr, IntPtr pStm, Guid* riid, IntPtr* ppv) @@ -204,7 +204,7 @@ private static int Do_Abi_UnmarshalInterface_3(IntPtr thisPtr, IntPtr pStm, Guid return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int Do_Abi_ReleaseMarshalData_4(IntPtr thisPtr, IntPtr pStm) @@ -221,7 +221,7 @@ private static int Do_Abi_ReleaseMarshalData_4(IntPtr thisPtr, IntPtr pStm) return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int Do_Abi_DisconnectObject_5(IntPtr thisPtr, uint dwReserved) diff --git a/src/WinRT.Runtime/Interop/IWeakReferenceSource.net5.cs b/src/WinRT.Runtime/Interop/IWeakReferenceSource.net5.cs index 42219959e..b5f11f6f4 100644 --- a/src/WinRT.Runtime/Interop/IWeakReferenceSource.net5.cs +++ b/src/WinRT.Runtime/Interop/IWeakReferenceSource.net5.cs @@ -6,15 +6,25 @@ namespace WinRT.Interop { [WindowsRuntimeType] - [Guid("00000038-0000-0000-C000-000000000046")] - public interface IWeakReferenceSource + [Guid("00000038-0000-0000-C000-000000000046")] +#if EMBED + internal +#else + public +#endif + interface IWeakReferenceSource { IWeakReference GetWeakReference(); } [WindowsRuntimeType] - [Guid("00000037-0000-0000-C000-000000000046")] - public interface IWeakReference + [Guid("00000037-0000-0000-C000-000000000046")] +#if EMBED + internal +#else + public +#endif + interface IWeakReference { IObjectReference Resolve(Guid riid); } diff --git a/src/WinRT.Runtime/Interop/IWeakReferenceSource.netstandard2.0.cs b/src/WinRT.Runtime/Interop/IWeakReferenceSource.netstandard2.0.cs index 120f1e2fa..db890af34 100644 --- a/src/WinRT.Runtime/Interop/IWeakReferenceSource.netstandard2.0.cs +++ b/src/WinRT.Runtime/Interop/IWeakReferenceSource.netstandard2.0.cs @@ -7,14 +7,24 @@ namespace WinRT.Interop { [WindowsRuntimeType] [Guid("00000038-0000-0000-C000-000000000046")] - public interface IWeakReferenceSource +#if EMBED + internal +#else + public +#endif + interface IWeakReferenceSource { IWeakReference GetWeakReference(); } [WindowsRuntimeType] [Guid("00000037-0000-0000-C000-000000000046")] - public interface IWeakReference +#if EMBED + internal +#else + public +#endif + interface IWeakReference { IObjectReference Resolve(Guid riid); } diff --git a/src/WinRT.Runtime/Interop/StandardDelegates.cs b/src/WinRT.Runtime/Interop/StandardDelegates.cs index 9e8eae995..02bdd6439 100644 --- a/src/WinRT.Runtime/Interop/StandardDelegates.cs +++ b/src/WinRT.Runtime/Interop/StandardDelegates.cs @@ -67,7 +67,17 @@ namespace WinRT.Interop [EditorBrowsable(EditorBrowsableState.Never)] public delegate int _put_PropertyAsString(IntPtr thisPtr, IntPtr value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _add_EventHandler(IntPtr thisPtr, IntPtr handler, out EventRegistrationToken token); - [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _remove_EventHandler(IntPtr thisPtr, EventRegistrationToken token); +#if EMBED + internal +#else + public +#endif + delegate int _add_EventHandler(IntPtr thisPtr, IntPtr handler, out EventRegistrationToken token); + [EditorBrowsable(EditorBrowsableState.Never)] +#if EMBED + internal +#else + public +#endif + delegate int _remove_EventHandler(IntPtr thisPtr, EventRegistrationToken token); } diff --git a/src/WinRT.Runtime/Marshalers.cs b/src/WinRT.Runtime/Marshalers.cs index 3842b3b15..595dcc4b9 100644 --- a/src/WinRT.Runtime/Marshalers.cs +++ b/src/WinRT.Runtime/Marshalers.cs @@ -1,14 +1,7 @@ using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; +using System.Linq.Expressions; using System.Reflection; using System.Runtime.InteropServices; -using System.Numerics; -using System.Security.Cryptography; -using System.Text; -using System.Linq.Expressions; -using System.Collections.Concurrent; using WinRT.Interop; #pragma warning disable 0169 // The field 'xxx' is never used @@ -30,7 +23,12 @@ public static void Dispose(this GCHandle handle) // TODO: minimize heap allocations for marshalers by eliminating explicit try/finally // and adopting ref structs with non-IDisposable Dispose and 'using var ...' pattern, // as well as passing marshalers to FromAbi by ref so they can be conditionally disposed. - public class MarshalString +#if EMBED + internal +#else + public +#endif + class MarshalString { private IntPtr _header; public GCHandle _gchandle; @@ -174,10 +172,6 @@ public static unsafe string[] FromAbiArray(object box) return null; } var abi = ((int length, IntPtr data))box; - if (abi.data == IntPtr.Zero) - { - return null; - } string[] array = new string[abi.length]; var data = (IntPtr*)abi.data.ToPointer(); for (int i = 0; i < abi.length; i++) @@ -277,11 +271,16 @@ public static unsafe void DisposeAbiArray(object box) } } - public struct MarshalBlittable +#if EMBED + internal +#else + public +#endif + struct MarshalBlittable { public struct MarshalerArray { - public MarshalerArray(Array array) => _gchandle = array is null ? default : GCHandle.Alloc(array, GCHandleType.Pinned); + public MarshalerArray(Array array) => _gchandle = GCHandle.Alloc(array, GCHandleType.Pinned); public void Dispose() => _gchandle.Dispose(); public GCHandle _gchandle; @@ -292,7 +291,7 @@ public struct MarshalerArray public static (int length, IntPtr data) GetAbiArray(object box) { var m = (MarshalerArray)box; - return m._gchandle.IsAllocated ? (((Array)m._gchandle.Target).Length, m._gchandle.AddrOfPinnedObject()) : (0, IntPtr.Zero); + return (((Array)m._gchandle.Target).Length, m._gchandle.AddrOfPinnedObject()); } public static unsafe T[] FromAbiArray(object box) @@ -302,10 +301,6 @@ public static unsafe T[] FromAbiArray(object box) return null; } var abi = ((int length, IntPtr data))box; - if (abi.data == IntPtr.Zero) - { - return null; - } var abiSpan = new ReadOnlySpan(abi.data.ToPointer(), abi.length); return abiSpan.ToArray(); } @@ -351,15 +346,37 @@ public static void DisposeAbiArray(object box) } } - public class MarshalGeneric +#if EMBED + internal +#else + public +#endif + class MarshalGeneric { protected static readonly Type HelperType = typeof(T).GetHelperType(); protected static readonly Type AbiType = typeof(T).GetAbiType(); protected static readonly Type MarshalerType = typeof(T).GetMarshalerType(); internal static readonly Type MarshalerArrayType = typeof(T).GetMarshalerArrayType(); - public static readonly Func CreateMarshaler = (T value) => CreateMarshalerLazy.Value(value); - private static readonly Lazy> CreateMarshalerLazy = new(BindCreateMarshaler); + static MarshalGeneric() + { + CreateMarshaler = BindCreateMarshaler(); + GetAbi = BindGetAbi(); + FromAbi = BindFromAbi(); + CopyAbi = BindCopyAbi(); + FromManaged = BindFromManaged(); + CopyManaged = BindCopyManaged(); + DisposeMarshaler = BindDisposeMarshaler(); + DisposeAbi = BindDisposeAbi(); + CreateMarshalerArray = BindCreateMarshalerArray(); + GetAbiArray = BindGetAbiArray(); + FromAbiArray = BindFromAbiArray(); + FromManagedArray = BindFromManagedArray(); + DisposeMarshalerArray = BindDisposeMarshalerArray(); + DisposeAbiArray = BindDisposeAbiArray(); + } + + public static readonly Func CreateMarshaler; private static Func BindCreateMarshaler() { var parms = new[] { Expression.Parameter(typeof(T), "arg") }; @@ -368,8 +385,7 @@ private static Func BindCreateMarshaler() typeof(object)), parms).Compile(); } - public static readonly Func GetAbi = (object objRef) => GetAbiLazy.Value(objRef); - private static readonly Lazy> GetAbiLazy = new(BindGetAbi); + public static readonly Func GetAbi; private static Func BindGetAbi() { var parms = new[] { Expression.Parameter(typeof(object), "arg") }; @@ -379,8 +395,7 @@ private static Func BindGetAbi() typeof(object)), parms).Compile(); } - public static readonly Action CopyAbi = (object box, IntPtr dest) => CopyAbiLazy.Value(box, dest); - private static readonly Lazy> CopyAbiLazy = new(BindCopyAbi); + public static readonly Action CopyAbi; private static Action BindCopyAbi() { var copyAbi = HelperType.GetMethod("CopyAbi", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -391,8 +406,7 @@ private static Action BindCopyAbi() new Expression[] { Expression.Convert(parms[0], MarshalerType), parms[1] }), parms).Compile(); } - public static readonly Func FromAbi = (object box) => FromAbiLazy.Value(box); - private static readonly Lazy> FromAbiLazy = new(BindFromAbi); + public static readonly Func FromAbi; private static Func BindFromAbi() { var parms = new[] { Expression.Parameter(typeof(object), "arg") }; @@ -401,8 +415,7 @@ private static Func BindFromAbi() new[] { Expression.Convert(parms[0], AbiType) }), parms).Compile(); } - public static readonly Func FromManaged = (T value) => FromManagedLazy.Value(value); - private static readonly Lazy> FromManagedLazy = new(BindFromManaged); + public static readonly Func FromManaged; private static Func BindFromManaged() { var parms = new[] { Expression.Parameter(typeof(T), "arg") }; @@ -411,8 +424,7 @@ private static Func BindFromManaged() typeof(object)), parms).Compile(); } - public static readonly Action CopyManaged = (T value, IntPtr dest) => CopyManagedLazy.Value(value, dest); - private static readonly Lazy> CopyManagedLazy = new(BindCopyManaged); + public static readonly Action CopyManaged; private static Action BindCopyManaged() { var copyManaged = HelperType.GetMethod("CopyManaged", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -422,8 +434,7 @@ private static Action BindCopyManaged() Expression.Call(copyManaged, parms), parms).Compile(); } - public static readonly Action DisposeMarshaler = (object objRef) => DisposeMarshalerLazy.Value(objRef); - private static readonly Lazy> DisposeMarshalerLazy = new(BindDisposeMarshaler); + public static readonly Action DisposeMarshaler; private static Action BindDisposeMarshaler() { var parms = new[] { Expression.Parameter(typeof(object), "arg") }; @@ -432,8 +443,7 @@ private static Action BindDisposeMarshaler() new[] { Expression.Convert(parms[0], MarshalerType) }), parms).Compile(); } - internal static readonly Action DisposeAbi = (object box) => DisposeAbiLazy.Value(box); - private static readonly Lazy> DisposeAbiLazy = new(BindDisposeAbi); + internal static readonly Action DisposeAbi; private static Action BindDisposeAbi() { var disposeAbi = HelperType.GetMethod("DisposeAbi", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -443,8 +453,7 @@ private static Action BindDisposeAbi() Expression.Call(disposeAbi, new[] { Expression.Convert(parms[0], AbiType) }), parms).Compile(); } - internal static readonly Func CreateMarshalerArray = (T[] array) => CreateMarshalerArrayLazy.Value(array); - private static readonly Lazy> CreateMarshalerArrayLazy = new(BindCreateMarshalerArray); + internal static readonly Func CreateMarshalerArray; private static Func BindCreateMarshalerArray() { var createMarshalerArray = HelperType.GetMethod("CreateMarshalerArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -454,8 +463,7 @@ private static Func BindCreateMarshalerArray() Expression.Convert(Expression.Call(createMarshalerArray, parms), typeof(object)), parms).Compile(); } - internal static readonly Func GetAbiArray = (object box) => GetAbiArrayLazy.Value(box); - private static readonly Lazy> GetAbiArrayLazy = new(BindGetAbiArray); + internal static readonly Func GetAbiArray; private static Func BindGetAbiArray() { var getAbiArray = HelperType.GetMethod("GetAbiArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -465,8 +473,7 @@ private static Func BindCreateMarshalerArray() Expression.Convert(Expression.Call(getAbiArray, parms), typeof((int, IntPtr))), parms).Compile(); } - internal static readonly Func FromAbiArray = (object box) => FromAbiArrayLazy.Value(box); - private static readonly Lazy> FromAbiArrayLazy = new(BindFromAbiArray); + internal static readonly Func FromAbiArray; private static Func BindFromAbiArray() { var fromAbiArray = HelperType.GetMethod("FromAbiArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -476,8 +483,7 @@ private static Func BindFromAbiArray() Expression.Call(fromAbiArray, parms), parms).Compile(); } - internal static readonly Func FromManagedArray = (T[] array) => FromManagedArrayLazy.Value(array); - private static readonly Lazy> FromManagedArrayLazy = new(BindFromManagedArray); + internal static readonly Func FromManagedArray; private static Func BindFromManagedArray() { var fromManagedArray = HelperType.GetMethod("FromManagedArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -487,8 +493,7 @@ private static Func BindFromAbiArray() Expression.Convert(Expression.Call(fromManagedArray, parms), typeof((int, IntPtr))), parms).Compile(); } - internal static readonly Action DisposeMarshalerArray = (object box) => DisposeMarshalerArrayLazy.Value(box); - private static readonly Lazy> DisposeMarshalerArrayLazy = new(BindDisposeMarshalerArray); + internal static readonly Action DisposeMarshalerArray; private static Action BindDisposeMarshalerArray() { var disposeMarshalerArray = HelperType.GetMethod("DisposeMarshalerArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -498,8 +503,7 @@ private static Action BindDisposeMarshalerArray() Expression.Call(disposeMarshalerArray, Expression.Convert(parms[0], MarshalerArrayType)), parms).Compile(); } - internal static readonly Action DisposeAbiArray = (object box) => DisposeAbiArrayLazy.Value(box); - private static readonly Lazy> DisposeAbiArrayLazy = new(BindDisposeAbiArray); + internal static readonly Action DisposeAbiArray; private static Action BindDisposeAbiArray() { var disposeAbiArray = HelperType.GetMethod("DisposeAbiArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -515,10 +519,15 @@ private static unsafe void CopyManagedFallback(T value, IntPtr dest) (value is null) ? IntPtr.Zero : ((IObjectReference) CreateMarshaler(value)).GetRef(); } - internal static unsafe void CopyManagedArray(T[] array, IntPtr data) => MarshalInterfaceHelper.CopyManagedArray(array, data, CopyManagedLazy.Value ?? CopyManagedFallback); + internal static unsafe void CopyManagedArray(T[] array, IntPtr data) => MarshalInterfaceHelper.CopyManagedArray(array, data, CopyManaged ?? CopyManagedFallback); } - public class MarshalNonBlittable : MarshalGeneric +#if EMBED + internal +#else + public +#endif + class MarshalNonBlittable : MarshalGeneric { private static readonly new Type AbiType = typeof(T).IsEnum ? Enum.GetUnderlyingType(typeof(T)) : MarshalGeneric.AbiType; @@ -587,10 +596,6 @@ public void Dispose() return null; } var abi = ((int length, IntPtr data))box; - if (abi.data == IntPtr.Zero) - { - return null; - } var array = new T[abi.length]; var data = (byte*)abi.data.ToPointer(); var abi_element_size = Marshal.SizeOf(AbiType); @@ -706,7 +711,12 @@ public static unsafe void DisposeAbiArrayElements((int length, IntPtr data) abi) } } - public class MarshalInterfaceHelper +#if EMBED + internal +#else + public +#endif + class MarshalInterfaceHelper { public struct MarshalerArray { @@ -771,10 +781,6 @@ public static unsafe T[] FromAbiArray(object box, Func fromAbi) return null; } var abi = ((int length, IntPtr data))box; - if (abi.data == IntPtr.Zero) - { - return null; - } var array = new T[abi.length]; var data = (IntPtr*)abi.data.ToPointer(); for (int i = 0; i < abi.length; i++) @@ -890,14 +896,17 @@ public static void DisposeMarshaler(IObjectReference objRef) public static void DisposeAbi(IntPtr ptr) { if (ptr == IntPtr.Zero) return; - unsafe - { - (**(IUnknownVftbl**)ptr).Release(ptr); - } + // TODO: this should be a direct v-table call when function pointers are a thing + ObjectReference.Attach(ref ptr).Dispose(); } } - public struct MarshalInterface +#if EMBED + internal +#else + public +#endif + struct MarshalInterface { private static readonly Type HelperType = typeof(T).GetHelperType(); private static Func _ToAbi; @@ -1005,7 +1014,8 @@ private static Func BindToAbi() private static Func BindAs() { - var vftblType = HelperType.FindVftblType(); + var helperType = typeof(T).GetHelperType(); + var vftblType = helperType.FindVftblType(); if (vftblType is not null) { var parms = new[] { Expression.Parameter(typeof(IObjectReference), "arg") }; @@ -1017,13 +1027,18 @@ private static Func BindAs() } else { - Guid iid = GuidGenerator.GetIID(HelperType); + Guid iid = GuidGenerator.GetIID(helperType); return obj => obj.As(iid); } } } - static public class MarshalInspectable +#if EMBED + internal +#else + public +#endif + static class MarshalInspectable { public static IObjectReference CreateMarshaler(T o, bool unwrapObject = true) { @@ -1121,7 +1136,12 @@ public static unsafe void CopyManaged(T o, IntPtr dest, bool unwrapObject = true } - static public class MarshalDelegate +#if EMBED + internal +#else + public +#endif + static class MarshalDelegate { public static IObjectReference CreateMarshaler(object o, Guid delegateIID, bool unwrapObject = true) { @@ -1141,7 +1161,12 @@ public static IObjectReference CreateMarshaler(object o, Guid delegateIID, bool } } - public class Marshaler +#if EMBED + internal +#else + public +#endif + class Marshaler { static Marshaler() { @@ -1181,10 +1206,10 @@ static Marshaler() CopyManaged = MarshalGeneric.CopyManaged; DisposeMarshaler = MarshalGeneric.DisposeMarshaler; DisposeAbi = MarshalGeneric.DisposeAbi; - CreateMarshalerArray = MarshalGeneric.CreateMarshalerArray; - GetAbiArray = MarshalGeneric.GetAbiArray; - FromAbiArray = MarshalGeneric.FromAbiArray; - FromManagedArray = MarshalGeneric.FromManagedArray; + CreateMarshalerArray = (T[] array) => MarshalGeneric.CreateMarshalerArray(array); + GetAbiArray = (object box) => MarshalGeneric.GetAbiArray(box); + FromAbiArray = (object box) => MarshalGeneric.FromAbiArray(box); + FromManagedArray = (T[] array) => MarshalGeneric.FromManagedArray(array); CopyManagedArray = (T[] array, IntPtr data) => MarshalGeneric.CopyManagedArray(array, data); DisposeMarshalerArray = (object box) => MarshalInterface.DisposeMarshalerArray(box); DisposeAbiArray = (object box) => MarshalInterface.DisposeAbiArray(box); @@ -1299,13 +1324,13 @@ unsafe void CopyEnum(object value, IntPtr dest) CopyManaged = MarshalGeneric.CopyManaged; DisposeMarshaler = MarshalGeneric.DisposeMarshaler; DisposeAbi = MarshalGeneric.DisposeAbi; - CreateMarshalerArray = MarshalGeneric.CreateMarshalerArray; - GetAbiArray = MarshalGeneric.GetAbiArray; - FromAbiArray = MarshalGeneric.FromAbiArray; - FromManagedArray = MarshalGeneric.FromManagedArray; + CreateMarshalerArray = (T[] array) => MarshalGeneric.CreateMarshalerArray(array); + GetAbiArray = (object box) => MarshalGeneric.GetAbiArray(box); + FromAbiArray = (object box) => MarshalGeneric.FromAbiArray(box); + FromManagedArray = (T[] array) => MarshalGeneric.FromManagedArray(array); CopyManagedArray = (T[] array, IntPtr data) => MarshalGeneric.CopyManagedArray(array, data); - DisposeMarshalerArray = MarshalGeneric.DisposeMarshalerArray; - DisposeAbiArray = MarshalGeneric.DisposeAbiArray; + DisposeMarshalerArray = (object box) => MarshalGeneric.DisposeMarshalerArray(box); + DisposeAbiArray = (object box) => MarshalGeneric.DisposeAbiArray(box); } RefAbiType = AbiType.MakeByRefType(); } diff --git a/src/WinRT.Runtime/Module.cs b/src/WinRT.Runtime/Module.cs index c7da65e22..636144eed 100644 --- a/src/WinRT.Runtime/Module.cs +++ b/src/WinRT.Runtime/Module.cs @@ -1,3 +1,3 @@ -#if !NETSTANDARD2_0 +#if NET [assembly: global::System.Runtime.Versioning.SupportedOSPlatform("Windows")] #endif diff --git a/src/WinRT.Runtime/MonoSupport.cs b/src/WinRT.Runtime/MonoSupport.cs index 41d7d3e27..3520d7820 100644 --- a/src/WinRT.Runtime/MonoSupport.cs +++ b/src/WinRT.Runtime/MonoSupport.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Runtime.InteropServices; -using System.Text; #pragma warning disable 0169 // The field 'xxx' is never used #pragma warning disable 0649 // Field 'xxx' is never assigned to, and will always have its default value @@ -117,5 +116,4 @@ public void Dispose() } } } - } diff --git a/src/WinRT.Runtime/ObjectReference.cs b/src/WinRT.Runtime/ObjectReference.cs index 9fd385317..2c547868c 100644 --- a/src/WinRT.Runtime/ObjectReference.cs +++ b/src/WinRT.Runtime/ObjectReference.cs @@ -1,10 +1,8 @@ using System; using System.Collections.Concurrent; -using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Text; using WinRT.Interop; #pragma warning disable 0169 // The field 'xxx' is never used @@ -12,11 +10,17 @@ namespace WinRT { - public abstract class IObjectReference : IDisposable + +#if EMBED + internal +#else + public +#endif + abstract class IObjectReference : IDisposable { protected bool disposed; private readonly IntPtr _thisPtr; - private object _disposedLock = new object(); + private object _disposedLock = new object(); private IntPtr _referenceTrackerPtr; public IntPtr ThisPtr @@ -26,61 +30,61 @@ public IntPtr ThisPtr ThrowIfDisposed(); return GetThisPtrForCurrentContext(); } - } - - private protected IntPtr ThisPtrFromOriginalContext - { + } + + private protected IntPtr ThisPtrFromOriginalContext + { get { ThrowIfDisposed(); return _thisPtr; } - } - -#if DEBUG - private unsafe uint RefCount - { - get - { - VftblIUnknown.AddRef(ThisPtr); - return VftblIUnknown.Release(ThisPtr); - } - } - - private bool BreakOnDispose { get; set; } -#endif - - internal bool IsAggregated { get; set; } - - internal bool PreventReleaseOnDispose { get; set; } - - internal bool PreventReleaseFromTrackerSourceOnDispose { get; set; } - - internal unsafe IntPtr ReferenceTrackerPtr - { - get - { - return _referenceTrackerPtr; - } - - set - { - _referenceTrackerPtr = value; - if (_referenceTrackerPtr != IntPtr.Zero) - { - ReferenceTracker.IUnknownVftbl.AddRef(_referenceTrackerPtr); - AddRefFromTrackerSource(); - } - } - } - - internal unsafe IReferenceTrackerVftbl ReferenceTracker - { - get - { - ThrowIfDisposed(); - return **(IReferenceTrackerVftbl**)ReferenceTrackerPtr; - } + } + +#if DEBUG + private unsafe uint RefCount + { + get + { + VftblIUnknown.AddRef(ThisPtr); + return VftblIUnknown.Release(ThisPtr); + } + } + + private bool BreakOnDispose { get; set; } +#endif + + internal bool IsAggregated { get; set; } + + internal bool PreventReleaseOnDispose { get; set; } + + internal bool PreventReleaseFromTrackerSourceOnDispose { get; set; } + + internal unsafe IntPtr ReferenceTrackerPtr + { + get + { + return _referenceTrackerPtr; + } + + set + { + _referenceTrackerPtr = value; + if (_referenceTrackerPtr != IntPtr.Zero) + { + ReferenceTracker.IUnknownVftbl.AddRef(_referenceTrackerPtr); + AddRefFromTrackerSource(); + } + } + } + + internal unsafe IReferenceTrackerVftbl ReferenceTracker + { + get + { + ThrowIfDisposed(); + return **(IReferenceTrackerVftbl**)ReferenceTrackerPtr; + } } protected unsafe IUnknownVftbl VftblIUnknown @@ -90,8 +94,8 @@ protected unsafe IUnknownVftbl VftblIUnknown ThrowIfDisposed(); return **(IUnknownVftbl**)ThisPtr; } - } - + } + private protected unsafe IUnknownVftbl VftblIUnknownFromOriginalContext { get @@ -117,8 +121,8 @@ protected IObjectReference(IntPtr thisPtr) public ObjectReference As() => As(GuidGenerator.GetIID(typeof(T))); public unsafe ObjectReference As(Guid iid) - { - Marshal.ThrowExceptionForHR(TryAs(iid, out var objRef)); + { + Marshal.ThrowExceptionForHR(TryAs(iid, out var objRef)); return objRef; } @@ -140,7 +144,7 @@ public unsafe TInterface AsInterface() } } -#if NETSTANDARD2_0 +#if !NET return (TInterface)typeof(TInterface).GetHelperType().GetConstructor(new[] { typeof(IObjectReference) }).Invoke(new object[] { this }); #else return (TInterface)(object)new WinRT.IInspectable(this); @@ -150,40 +154,40 @@ public unsafe TInterface AsInterface() public int TryAs(out ObjectReference objRef) => TryAs(GuidGenerator.GetIID(typeof(T)), out objRef); public virtual unsafe int TryAs(Guid iid, out ObjectReference objRef) - { - objRef = null; - ThrowIfDisposed(); - int hr = VftblIUnknown.QueryInterface(ThisPtr, ref iid, out IntPtr thatPtr); - if (hr >= 0) - { - if (IsAggregated) - { - Marshal.Release(thatPtr); - } - AddRefFromTrackerSource(); - - objRef = ObjectReference.Attach(ref thatPtr); - objRef.IsAggregated = IsAggregated; - objRef.PreventReleaseOnDispose = IsAggregated; - objRef.ReferenceTrackerPtr = ReferenceTrackerPtr; - } + { + objRef = null; + ThrowIfDisposed(); + int hr = VftblIUnknown.QueryInterface(ThisPtr, ref iid, out IntPtr thatPtr); + if (hr >= 0) + { + if (IsAggregated) + { + Marshal.Release(thatPtr); + } + AddRefFromTrackerSource(); + + objRef = ObjectReference.Attach(ref thatPtr); + objRef.IsAggregated = IsAggregated; + objRef.PreventReleaseOnDispose = IsAggregated; + objRef.ReferenceTrackerPtr = ReferenceTrackerPtr; + } return hr; - } - - // Used only as part of the GetInterface implementation where the - // result is an reference passed across the ABI and doesn't need to - // be tracked as an internal reference. This is separate to handle - // tear off aggregate scenario where releasing an reference can end up - // deleting the tear off interface. + } + + // Used only as part of the GetInterface implementation where the + // result is an reference passed across the ABI and doesn't need to + // be tracked as an internal reference. This is separate to handle + // tear off aggregate scenario where releasing an reference can end up + // deleting the tear off interface. public virtual unsafe int TryAs(Guid iid, out IntPtr ppv) - { - ppv = IntPtr.Zero; - ThrowIfDisposed(); - int hr = VftblIUnknown.QueryInterface(ThisPtr, ref iid, out IntPtr thatPtr); - if (hr >= 0) - { - ppv = thatPtr; - } + { + ppv = IntPtr.Zero; + ThrowIfDisposed(); + int hr = VftblIUnknown.QueryInterface(ThisPtr, ref iid, out IntPtr thatPtr); + if (hr >= 0) + { + ppv = thatPtr; + } return hr; } @@ -203,18 +207,18 @@ public T AsType() public IntPtr GetRef() { ThrowIfDisposed(); - AddRef(false); + AddRef(false); return ThisPtr; } protected void ThrowIfDisposed() - { - if (disposed) - { - lock (_disposedLock) - { - if (disposed) throw new ObjectDisposedException("ObjectReference"); - } + { + if (disposed) + { + lock (_disposedLock) + { + if (disposed) throw new ObjectDisposedException("ObjectReference"); + } } } @@ -226,33 +230,33 @@ public void Dispose() protected virtual void Dispose(bool disposing) { - lock (_disposedLock) - { + lock (_disposedLock) + { if (disposed) { return; - } -#if DEBUG - if (BreakOnDispose && System.Diagnostics.Debugger.IsAttached) - { - System.Diagnostics.Debugger.Break(); - } -#endif - - if (!PreventReleaseOnDispose) - { - Release(); - } - + } +#if DEBUG + if (BreakOnDispose && System.Diagnostics.Debugger.IsAttached) + { + System.Diagnostics.Debugger.Break(); + } +#endif + + if (!PreventReleaseOnDispose) + { + Release(); + } + DisposeTrackerSource(); disposed = true; - } + } } internal bool Resurrect() { - lock (_disposedLock) - { + lock (_disposedLock) + { if (!disposed) { return false; @@ -261,18 +265,18 @@ internal bool Resurrect() ResurrectTrackerSource(); AddRef(); GC.ReRegisterForFinalize(this); - return true; - } - } - - protected virtual unsafe void AddRef(bool refFromTrackerSource) - { - VftblIUnknown.AddRef(ThisPtr); - if(refFromTrackerSource) - { - AddRefFromTrackerSource(); - } - } + return true; + } + } + + protected virtual unsafe void AddRef(bool refFromTrackerSource) + { + VftblIUnknown.AddRef(ThisPtr); + if(refFromTrackerSource) + { + AddRefFromTrackerSource(); + } + } protected virtual unsafe void AddRef() { @@ -281,14 +285,14 @@ protected virtual unsafe void AddRef() protected virtual unsafe void Release() { - ReleaseFromTrackerSource(); - VftblIUnknown.Release(ThisPtr); - } - + ReleaseFromTrackerSource(); + VftblIUnknown.Release(ThisPtr); + } + private protected unsafe void ReleaseWithoutContext() { - ReleaseFromTrackerSource(); - VftblIUnknownFromOriginalContext.Release(ThisPtrFromOriginalContext); + ReleaseFromTrackerSource(); + VftblIUnknownFromOriginalContext.Release(ThisPtrFromOriginalContext); } internal unsafe bool IsReferenceToManagedObject @@ -297,56 +301,61 @@ internal unsafe bool IsReferenceToManagedObject { return VftblIUnknown.Equals(IUnknownVftbl.AbiToProjectionVftbl); } - } - - internal unsafe void AddRefFromTrackerSource() - { - if (ReferenceTrackerPtr != IntPtr.Zero) - { - ReferenceTracker.AddRefFromTrackerSource(ReferenceTrackerPtr); - } - } - - internal unsafe void ReleaseFromTrackerSource() - { - if (ReferenceTrackerPtr != IntPtr.Zero) - { - ReferenceTracker.ReleaseFromTrackerSource(ReferenceTrackerPtr); - } - } - - private unsafe void ResurrectTrackerSource() - { - if (ReferenceTrackerPtr != IntPtr.Zero) - { - ReferenceTracker.IUnknownVftbl.AddRef(ReferenceTrackerPtr); - if (!PreventReleaseFromTrackerSourceOnDispose) - { - ReferenceTracker.AddRefFromTrackerSource(ReferenceTrackerPtr); - } - } - } - - private unsafe void DisposeTrackerSource() - { - if (ReferenceTrackerPtr != IntPtr.Zero) - { - if (!PreventReleaseFromTrackerSourceOnDispose) - { - ReferenceTracker.ReleaseFromTrackerSource(ReferenceTrackerPtr); - } - ReferenceTracker.IUnknownVftbl.Release(ReferenceTrackerPtr); - } - } - - private protected virtual IntPtr GetThisPtrForCurrentContext() - { - return ThisPtrFromOriginalContext; + } + + internal unsafe void AddRefFromTrackerSource() + { + if (ReferenceTrackerPtr != IntPtr.Zero) + { + ReferenceTracker.AddRefFromTrackerSource(ReferenceTrackerPtr); + } + } + + internal unsafe void ReleaseFromTrackerSource() + { + if (ReferenceTrackerPtr != IntPtr.Zero) + { + ReferenceTracker.ReleaseFromTrackerSource(ReferenceTrackerPtr); + } + } + + private unsafe void ResurrectTrackerSource() + { + if (ReferenceTrackerPtr != IntPtr.Zero) + { + ReferenceTracker.IUnknownVftbl.AddRef(ReferenceTrackerPtr); + if (!PreventReleaseFromTrackerSourceOnDispose) + { + ReferenceTracker.AddRefFromTrackerSource(ReferenceTrackerPtr); + } + } + } + + private unsafe void DisposeTrackerSource() + { + if (ReferenceTrackerPtr != IntPtr.Zero) + { + if (!PreventReleaseFromTrackerSourceOnDispose) + { + ReferenceTracker.ReleaseFromTrackerSource(ReferenceTrackerPtr); + } + ReferenceTracker.IUnknownVftbl.Release(ReferenceTrackerPtr); + } + } + + private protected virtual IntPtr GetThisPtrForCurrentContext() + { + return ThisPtrFromOriginalContext; } } - public class ObjectReference : IObjectReference - { +#if EMBED + internal +#else + public +#endif + class ObjectReference : IObjectReference + { private readonly T _vftbl; public T Vftbl { @@ -411,7 +420,7 @@ private static unsafe T GetVtable(IntPtr thisPtr) // Since it is a JIT time constant, this function will be branchless on .NET 5. // On .NET Standard 2.0, the IsReferenceOrContainsReferences method does not exist, // so we instead fall back to typeof(T).IsGenericType, which sadly is not a JIT-time constant. -#if NETSTANDARD2_0 +#if !NET if (typeof(T).IsGenericType) #else if (RuntimeHelpers.IsReferenceOrContainsReferences()) @@ -424,19 +433,19 @@ private static unsafe T GetVtable(IntPtr thisPtr) vftblT = Unsafe.AsRef(vftblPtr.Vftbl.ToPointer()); } return vftblT; - } - - private protected virtual T GetVftblForCurrentContext() - { - return _vftbl; + } + + private protected virtual T GetVftblForCurrentContext() + { + return _vftbl; } } internal class ObjectReferenceWithContext : ObjectReference { private readonly IntPtr _contextCallbackPtr; - private readonly IntPtr _contextToken; - private readonly Lazy>> _cachedContext; + private readonly IntPtr _contextToken; + private readonly Lazy>> _cachedContext; private readonly Lazy _agileReference; private readonly Guid _iid; @@ -444,121 +453,121 @@ internal ObjectReferenceWithContext(IntPtr thisPtr, IntPtr contextCallbackPtr, I :base(thisPtr) { _contextCallbackPtr = contextCallbackPtr; - _contextToken = contextToken; - _cachedContext = new Lazy>>(); - _agileReference = new Lazy(() => { - AgileReference agileReference = null; + _contextToken = contextToken; + _cachedContext = new Lazy>>(); + _agileReference = new Lazy(() => { + AgileReference agileReference = null; Context.CallInContext(_contextCallbackPtr, _contextToken, InitAgileReference, null); - return agileReference; - - void InitAgileReference() - { - agileReference = new AgileReference(this); - } - }); - } - + return agileReference; + + void InitAgileReference() + { + agileReference = new AgileReference(this); + } + }); + } + internal ObjectReferenceWithContext(IntPtr thisPtr, IntPtr contextCallbackPtr, IntPtr contextToken, Lazy agileReference, Guid iid) : base(thisPtr) - { + { _contextCallbackPtr = contextCallbackPtr; - _contextToken = contextToken; - _cachedContext = new Lazy>>(); + _contextToken = contextToken; + _cachedContext = new Lazy>>(); _agileReference = agileReference; _iid = iid; - } - - private protected override IntPtr GetThisPtrForCurrentContext() - { - ObjectReference cachedObjRef = GetCurrentContext(); - if (cachedObjRef == null) - { - return base.GetThisPtrForCurrentContext(); - } - - return cachedObjRef.ThisPtr; - } - - private protected override T GetVftblForCurrentContext() - { - ObjectReference cachedObjRef = GetCurrentContext(); - if (cachedObjRef == null) - { - return base.GetVftblForCurrentContext(); - } - - return cachedObjRef.Vftbl; - } - - // Gets the object reference with respect to the current context. - // If we are already on the same context as when this object reference was - // created or failed to switch context, null is returned as the current base - // object reference should be used. - private ObjectReference GetCurrentContext() - { - IntPtr currentContext = Context.GetContextToken(); - if (_contextCallbackPtr == IntPtr.Zero || currentContext == _contextToken) - { - return null; - } - - return _cachedContext.Value.GetOrAdd(currentContext, CreateForCurrentContext); - - ObjectReference CreateForCurrentContext(IntPtr _) - { - var agileReference = _agileReference.Value; - // We may fail to switch context and thereby not get an agile reference. - // In these cases, fallback to using the current context. - if (agileReference == null) - { - return null; - } - - using var referenceInContext = agileReference.Get(); - if (_iid == Guid.Empty) - { - return referenceInContext.TryAs(out var objRef) >= 0 ? objRef : null; - } - else - { - return referenceInContext.TryAs(_iid, out var objRef) >= 0 ? objRef : null; - } - } + } + + private protected override IntPtr GetThisPtrForCurrentContext() + { + ObjectReference cachedObjRef = GetCurrentContext(); + if (cachedObjRef == null) + { + return base.GetThisPtrForCurrentContext(); + } + + return cachedObjRef.ThisPtr; + } + + private protected override T GetVftblForCurrentContext() + { + ObjectReference cachedObjRef = GetCurrentContext(); + if (cachedObjRef == null) + { + return base.GetVftblForCurrentContext(); + } + + return cachedObjRef.Vftbl; + } + + // Gets the object reference with respect to the current context. + // If we are already on the same context as when this object reference was + // created or failed to switch context, null is returned as the current base + // object reference should be used. + private ObjectReference GetCurrentContext() + { + IntPtr currentContext = Context.GetContextToken(); + if (_contextCallbackPtr == IntPtr.Zero || currentContext == _contextToken) + { + return null; + } + + return _cachedContext.Value.GetOrAdd(currentContext, CreateForCurrentContext); + + ObjectReference CreateForCurrentContext(IntPtr _) + { + var agileReference = _agileReference.Value; + // We may fail to switch context and thereby not get an agile reference. + // In these cases, fallback to using the current context. + if (agileReference == null) + { + return null; + } + + using var referenceInContext = agileReference.Get(); + if (_iid == Guid.Empty) + { + return referenceInContext.TryAs(out var objRef) >= 0 ? objRef : null; + } + else + { + return referenceInContext.TryAs(_iid, out var objRef) >= 0 ? objRef : null; + } + } } protected override unsafe void Release() { - if (_cachedContext.IsValueCreated) - { - _cachedContext.Value.Clear(); + if (_cachedContext.IsValueCreated) + { + _cachedContext.Value.Clear(); } Context.CallInContext(_contextCallbackPtr, _contextToken, base.Release, ReleaseWithoutContext); Context.DisposeContextCallback(_contextCallbackPtr); - } - + } + public override unsafe int TryAs(Guid iid, out ObjectReference objRef) { - objRef = null; - - int hr = VftblIUnknown.QueryInterface(ThisPtr, ref iid, out IntPtr thatPtr); - if (hr >= 0) - { - if (IsAggregated) - { - Marshal.Release(thatPtr); - } - AddRefFromTrackerSource(); - - objRef = new ObjectReferenceWithContext(thatPtr, Context.GetContextCallback(), Context.GetContextToken(), _agileReference, iid) - { - IsAggregated = IsAggregated, - PreventReleaseOnDispose = IsAggregated, - ReferenceTrackerPtr = ReferenceTrackerPtr - }; - } - - return hr; - } - } + objRef = null; + + int hr = VftblIUnknown.QueryInterface(ThisPtr, ref iid, out IntPtr thatPtr); + if (hr >= 0) + { + if (IsAggregated) + { + Marshal.Release(thatPtr); + } + AddRefFromTrackerSource(); + + objRef = new ObjectReferenceWithContext(thatPtr, Context.GetContextCallback(), Context.GetContextToken(), _agileReference, iid) + { + IsAggregated = IsAggregated, + PreventReleaseOnDispose = IsAggregated, + ReferenceTrackerPtr = ReferenceTrackerPtr + }; + } + + return hr; + } + } } diff --git a/src/WinRT.Runtime/Projections.cs b/src/WinRT.Runtime/Projections.cs index be08c290a..af2402581 100644 --- a/src/WinRT.Runtime/Projections.cs +++ b/src/WinRT.Runtime/Projections.cs @@ -12,14 +12,19 @@ namespace WinRT { - public static class Projections +#if EMBED + internal +#else + public +#endif + static class Projections { private static readonly ReaderWriterLockSlim rwlock = new ReaderWriterLockSlim(); private static readonly Dictionary CustomTypeToHelperTypeMappings = new Dictionary(); private static readonly Dictionary CustomAbiTypeToTypeMappings = new Dictionary(); - private static readonly Dictionary CustomAbiTypeNameToTypeMappings = new Dictionary(StringComparer.Ordinal); + private static readonly Dictionary CustomAbiTypeNameToTypeMappings = new Dictionary(); private static readonly Dictionary CustomTypeToAbiTypeNameMappings = new Dictionary(); - private static readonly HashSet ProjectedRuntimeClassNames = new HashSet(StringComparer.Ordinal); + private static readonly HashSet ProjectedRuntimeClassNames = new HashSet(); private static readonly HashSet ProjectedCustomTypeRuntimeClasses = new HashSet(); static Projections() diff --git a/src/WinRT.Runtime/Projections/Bindable.netstandard2.0.cs b/src/WinRT.Runtime/Projections/Bindable.netstandard2.0.cs index 9d02ff70d..8032ec604 100644 --- a/src/WinRT.Runtime/Projections/Bindable.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/Bindable.netstandard2.0.cs @@ -408,8 +408,13 @@ namespace ABI.System.Collections using global::Microsoft.UI.Xaml.Interop; [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] - [Guid("036D2C08-DF29-41AF-8AA2-D774BE62BA6F")] - public unsafe class IEnumerable : global::System.Collections.IEnumerable, IBindableIterable + [Guid("036D2C08-DF29-41AF-8AA2-D774BE62BA6F")] +#if EMBED + internal +#else + public +#endif + unsafe class IEnumerable : global::System.Collections.IEnumerable, IBindableIterable { public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IEnumerable)); @@ -550,15 +555,25 @@ internal IEnumerable(ObjectReference obj) public IEnumerator GetEnumerator() => _FromIterable.GetEnumerator(); } - [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - public static class IEnumerable_Delegates + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] +#if EMBED + internal +#else + public +#endif + static class IEnumerable_Delegates { public unsafe delegate int First_0(IntPtr thisPtr, IntPtr* result); } [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] - [Guid("393DE7DE-6FD0-4C0D-BB71-47244A113E93")] - public unsafe class IList : global::System.Collections.IList + [Guid("393DE7DE-6FD0-4C0D-BB71-47244A113E93")] +#if EMBED + internal +#else + public +#endif + unsafe class IList : global::System.Collections.IList { public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IList)); diff --git a/src/WinRT.Runtime/Projections/DataErrorsChangedEventArgs.cs b/src/WinRT.Runtime/Projections/DataErrorsChangedEventArgs.cs index e717ca388..8fae089ae 100644 --- a/src/WinRT.Runtime/Projections/DataErrorsChangedEventArgs.cs +++ b/src/WinRT.Runtime/Projections/DataErrorsChangedEventArgs.cs @@ -72,7 +72,12 @@ namespace ABI.System.ComponentModel { [EditorBrowsable(EditorBrowsableState.Never)] [StructLayout(LayoutKind.Sequential)] - public unsafe struct DataErrorsChangedEventArgs +#if EMBED + internal +#else + public +#endif + unsafe struct DataErrorsChangedEventArgs { private static WeakLazy _factory = new WeakLazy(); @@ -132,7 +137,7 @@ public static IntPtr FromManaged(global::System.ComponentModel.DataErrorsChanged } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } + public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } public static string GetGuidSignature() { diff --git a/src/WinRT.Runtime/Projections/EventHandler.cs b/src/WinRT.Runtime/Projections/EventHandler.cs index 18ba38b9a..1e979851b 100644 --- a/src/WinRT.Runtime/Projections/EventHandler.cs +++ b/src/WinRT.Runtime/Projections/EventHandler.cs @@ -4,7 +4,7 @@ using System.ComponentModel; using System.Linq.Expressions; using System.Reflection; -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using WinRT; @@ -13,7 +13,12 @@ namespace ABI.System { [Guid("9DE1C535-6AE1-11E0-84E1-18A905BCC53F"), EditorBrowsable(EditorBrowsableState.Never)] - public static class EventHandler +#if EMBED + internal +#else + public +#endif + static class EventHandler { public static Guid PIID = GuidGenerator.CreateIID(typeof(global::System.EventHandler)); private static readonly global::System.Type Abi_Invoke_Type = Expression.GetDelegateType(new global::System.Type[] { typeof(void*), typeof(IntPtr), Marshaler.AbiType, typeof(int) }); @@ -44,36 +49,34 @@ public static IntPtr GetAbi(IObjectReference value) => value is null ? IntPtr.Zero : MarshalInterfaceHelper>.GetAbi(value); public static unsafe global::System.EventHandler FromAbi(IntPtr nativeDelegate) - { + { var abiDelegate = ComWrappersSupport.GetObjectReferenceForInterface(nativeDelegate)?.As(GuidGenerator.GetIID(typeof(EventHandler))); return abiDelegate is null ? null : (global::System.EventHandler)ComWrappersSupport.TryRegisterObjectForInterface(new global::System.EventHandler(new NativeDelegateWrapper(abiDelegate).Invoke), nativeDelegate); } [global::WinRT.ObjectReferenceWrapper(nameof(_nativeDelegate))] -#if NETSTANDARD2_0 +#if !NET private class NativeDelegateWrapper #else private class NativeDelegateWrapper : IWinRTObject #endif { - private readonly ObjectReference _nativeDelegate; + private readonly ObjectReference _nativeDelegate; public NativeDelegateWrapper(ObjectReference nativeDelegate) { _nativeDelegate = nativeDelegate; } -#if !NETSTANDARD2_0 +#if NET IObjectReference IWinRTObject.NativeObject => _nativeDelegate; bool IWinRTObject.HasUnwrappableNativeObject => true; - private Lazy> _lazyQueryInterfaceCache = new(); - ConcurrentDictionary IWinRTObject.QueryInterfaceCache => _lazyQueryInterfaceCache.Value; - private Lazy> _lazyAdditionalTypeData = new(); - ConcurrentDictionary IWinRTObject.AdditionalTypeData => _lazyAdditionalTypeData.Value; + ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); + ConcurrentDictionary IWinRTObject.AdditionalTypeData { get; } = new(); #endif public void Invoke(object sender, T args) - { + { IntPtr ThisPtr = _nativeDelegate.ThisPtr; var abiInvoke = Marshal.GetDelegateForFunctionPointer(_nativeDelegate.Vftbl.Invoke, Abi_Invoke_Type); IObjectReference __sender = default; @@ -119,12 +122,12 @@ private static unsafe int Do_Abi_Invoke(void* thisPtr, IntPtr sender, TAbi } return 0; } - } - + } + [Guid("c50898f6-c536-5f47-8583-8b2c2438a13b")] internal static class EventHandler { -#if NETSTANDARD2_0 +#if !NET private delegate int Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr args); #endif @@ -136,7 +139,7 @@ static unsafe EventHandler() AbiToProjectionVftable = new global::WinRT.Interop.IDelegateVftbl { IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, -#if NETSTANDARD2_0 +#if !NET Invoke = Marshal.GetFunctionPointerForDelegate(AbiInvokeDelegate = (Abi_Invoke)Do_Abi_Invoke) #else Invoke = (IntPtr)(delegate* unmanaged[Stdcall])&Do_Abi_Invoke @@ -145,51 +148,49 @@ static unsafe EventHandler() var nativeVftbl = ComWrappersSupport.AllocateVtableMemory(typeof(EventHandler), Marshal.SizeOf()); Marshal.StructureToPtr(AbiToProjectionVftable, nativeVftbl, false); AbiToProjectionVftablePtr = nativeVftbl; - } - -#if NETSTANDARD2_0 + } + +#if !NET public static global::System.Delegate AbiInvokeDelegate { get; } #endif public static unsafe IObjectReference CreateMarshaler(global::System.EventHandler managedDelegate) => managedDelegate is null ? null : MarshalDelegate.CreateMarshaler(managedDelegate, GuidGenerator.GetIID(typeof(EventHandler))); - public static IntPtr GetAbi(IObjectReference value) => + public static IntPtr GetAbi(IObjectReference value) => value is null ? IntPtr.Zero : MarshalInterfaceHelper>.GetAbi(value); public static unsafe global::System.EventHandler FromAbi(IntPtr nativeDelegate) - { + { var abiDelegate = ComWrappersSupport.GetObjectReferenceForInterface(nativeDelegate)?.As(GuidGenerator.GetIID(typeof(EventHandler))); return abiDelegate is null ? null : (global::System.EventHandler)ComWrappersSupport.TryRegisterObjectForInterface(new global::System.EventHandler(new NativeDelegateWrapper(abiDelegate).Invoke), nativeDelegate); } [global::WinRT.ObjectReferenceWrapper(nameof(_nativeDelegate))] -#if NETSTANDARD2_0 +#if !NET private class NativeDelegateWrapper #else private class NativeDelegateWrapper : IWinRTObject #endif { - private readonly ObjectReference _nativeDelegate; - + private readonly ObjectReference _nativeDelegate; + public NativeDelegateWrapper(ObjectReference nativeDelegate) { _nativeDelegate = nativeDelegate; } -#if !NETSTANDARD2_0 +#if NET IObjectReference IWinRTObject.NativeObject => _nativeDelegate; bool IWinRTObject.HasUnwrappableNativeObject => true; - private Lazy> _lazyQueryInterfaceCache = new(); - ConcurrentDictionary IWinRTObject.QueryInterfaceCache => _lazyQueryInterfaceCache.Value; - private Lazy> _lazyAdditionalTypeData = new(); - ConcurrentDictionary IWinRTObject.AdditionalTypeData => _lazyAdditionalTypeData.Value; + ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); + ConcurrentDictionary IWinRTObject.AdditionalTypeData { get; } = new(); #endif public unsafe void Invoke(object sender, EventArgs args) - { - IntPtr ThisPtr = _nativeDelegate.ThisPtr; -#if NETSTANDARD2_0 + { + IntPtr ThisPtr = _nativeDelegate.ThisPtr; +#if !NET var abiInvoke = Marshal.GetDelegateForFunctionPointer(_nativeDelegate.Vftbl.Invoke); #else var abiInvoke = (delegate* unmanaged[Stdcall])(_nativeDelegate.Vftbl.Invoke); @@ -218,9 +219,9 @@ public static IntPtr FromManaged(global::System.EventHandler managedDelegate) => public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper>.DisposeMarshaler(value); - public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper>.DisposeAbi(abi); - -#if !NETSTANDARD2_0 + public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper>.DisposeAbi(abi); + +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static unsafe int Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr args) @@ -244,7 +245,7 @@ private static unsafe int Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr ar } internal sealed unsafe class EventHandlerEventSource : EventSource - { + { internal EventHandlerEventSource(IObjectReference obj, delegate* unmanaged[Stdcall] addHandler, delegate* unmanaged[Stdcall] removeHandler) @@ -259,28 +260,28 @@ protected override void DisposeMarshaler(IObjectReference marshaler) => EventHandler.DisposeMarshaler(marshaler); protected override IntPtr GetAbi(IObjectReference marshaler) => - marshaler is null ? IntPtr.Zero : EventHandler.GetAbi(marshaler); - - protected override State CreateEventState() => - new EventState(_obj.ThisPtr, _index); - - private sealed class EventState : State - { - public EventState(IntPtr obj, int index) - : base(obj, index) - { - } - - protected override Delegate GetEventInvoke() - { - global::System.EventHandler handler = (global::System.Object obj, global::System.EventArgs e) => + marshaler is null ? IntPtr.Zero : EventHandler.GetAbi(marshaler); + + protected override State CreateEventState() => + new EventState(_obj.ThisPtr, _index); + + private sealed class EventState : State + { + public EventState(IntPtr obj, int index) + : base(obj, index) + { + } + + protected override Delegate GetEventInvoke() + { + global::System.EventHandler handler = (global::System.Object obj, global::System.EventArgs e) => { - var localDel = del; - if (localDel != null) - localDel.Invoke(obj, e); - }; - return handler; - } + var localDel = del; + if (localDel != null) + localDel.Invoke(obj, e); + }; + return handler; + } } } } diff --git a/src/WinRT.Runtime/Projections/Geometry.cs b/src/WinRT.Runtime/Projections/Geometry.cs index 84746bc42..5b64fbc3d 100644 --- a/src/WinRT.Runtime/Projections/Geometry.cs +++ b/src/WinRT.Runtime/Projections/Geometry.cs @@ -4,7 +4,7 @@ namespace Windows.Foundation { - internal class SR + internal class GSR { public static string ArgumentOutOfRange_NeedNonNegNum = "Non-negative number required."; } @@ -118,9 +118,9 @@ public Rect(float x, float height) { if (width < 0) - throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(width), GSR.ArgumentOutOfRange_NeedNonNegNum); if (height < 0) - throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(height), GSR.ArgumentOutOfRange_NeedNonNegNum); _x = x; _y = y; @@ -176,7 +176,7 @@ public double Width set { if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(Width), GSR.ArgumentOutOfRange_NeedNonNegNum); _width = (float)value; } @@ -188,7 +188,7 @@ public double Height set { if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(Height), GSR.ArgumentOutOfRange_NeedNonNegNum); _height = (float)value; } @@ -427,9 +427,9 @@ public struct Size public Size(float width, float height) { if (width < 0) - throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(width), GSR.ArgumentOutOfRange_NeedNonNegNum); if (height < 0) - throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(height), GSR.ArgumentOutOfRange_NeedNonNegNum); _width = width; _height = height; } @@ -442,7 +442,7 @@ public double Width set { if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(Width), GSR.ArgumentOutOfRange_NeedNonNegNum); _width = (float)value; } @@ -454,7 +454,7 @@ public double Height set { if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(Height), GSR.ArgumentOutOfRange_NeedNonNegNum); _height = (float)value; } @@ -590,28 +590,28 @@ public static string GetGuidSignature() } } -namespace System.Numerics -{ - public static class VectorExtensions - { - public static global::Windows.Foundation.Point ToPoint(this Vector2 vector) - { - return new global::Windows.Foundation.Point(vector.X, vector.Y); - } - - public static global::Windows.Foundation.Size ToSize(this Vector2 vector) - { - return new global::Windows.Foundation.Size(vector.X, vector.Y); - } - - public static Vector2 ToVector2(this global::Windows.Foundation.Point point) - { - return new Vector2((float)point.X, (float)point.Y); - } - - public static Vector2 ToVector2(this global::Windows.Foundation.Size size) - { - return new Vector2((float)size.Width, (float)size.Height); - } - } +namespace System.Numerics +{ + public static class VectorExtensions + { + public static global::Windows.Foundation.Point ToPoint(this Vector2 vector) + { + return new global::Windows.Foundation.Point(vector.X, vector.Y); + } + + public static global::Windows.Foundation.Size ToSize(this Vector2 vector) + { + return new global::Windows.Foundation.Size(vector.X, vector.Y); + } + + public static Vector2 ToVector2(this global::Windows.Foundation.Point point) + { + return new Vector2((float)point.X, (float)point.Y); + } + + public static Vector2 ToVector2(this global::Windows.Foundation.Size size) + { + return new Vector2((float)size.Width, (float)size.Height); + } + } } \ No newline at end of file diff --git a/src/WinRT.Runtime/Projections/ICommand.net5.cs b/src/WinRT.Runtime/Projections/ICommand.net5.cs index c5623e158..7233ab2be 100644 --- a/src/WinRT.Runtime/Projections/ICommand.net5.cs +++ b/src/WinRT.Runtime/Projections/ICommand.net5.cs @@ -15,7 +15,12 @@ namespace ABI.System.Windows.Input [EditorBrowsable(EditorBrowsableState.Never)] [Guid("E5AF3542-CA67-4081-995B-709DD13792DF")] [DynamicInterfaceCastableImplementation] - public unsafe interface ICommand : global::System.Windows.Input.ICommand +#if EMBED + internal +#else + public +#endif + unsafe interface ICommand : global::System.Windows.Input.ICommand { [Guid("E5AF3542-CA67-4081-995B-709DD13792DF")] public struct Vftbl @@ -190,7 +195,12 @@ private static EventHandlerEventSource _CanExecuteChanged(IWinRTObject _this) } [EditorBrowsable(EditorBrowsableState.Never)] - public static class ICommand_Delegates +#if EMBED + internal +#else + public +#endif + static class ICommand_Delegates { public unsafe delegate int add_CanExecuteChanged_0(IntPtr thisPtr, IntPtr handler, global::WinRT.EventRegistrationToken* token); public unsafe delegate int CanExecute_2(IntPtr thisPtr, IntPtr parameter, byte* result); diff --git a/src/WinRT.Runtime/Projections/ICommand.netstandard2.0.cs b/src/WinRT.Runtime/Projections/ICommand.netstandard2.0.cs index f071420ef..813db3ce7 100644 --- a/src/WinRT.Runtime/Projections/ICommand.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/ICommand.netstandard2.0.cs @@ -13,7 +13,12 @@ namespace ABI.System.Windows.Input { [global::WinRT.ObjectReferenceWrapper(nameof(_obj)), EditorBrowsable(EditorBrowsableState.Never)] [Guid("E5AF3542-CA67-4081-995B-709DD13792DF")] - public unsafe class ICommand : global::System.Windows.Input.ICommand +#if EMBED + internal +#else + public +#endif + unsafe class ICommand : global::System.Windows.Input.ICommand { [Guid("E5AF3542-CA67-4081-995B-709DD13792DF")] public struct Vftbl @@ -189,7 +194,12 @@ public unsafe void Execute(object parameter) } [EditorBrowsable(EditorBrowsableState.Never)] - public static class ICommand_Delegates +#if EMBED + internal +#else + public +#endif + static class ICommand_Delegates { public unsafe delegate int add_CanExecuteChanged_0(IntPtr thisPtr, IntPtr handler, global::WinRT.EventRegistrationToken* token); public unsafe delegate int CanExecute_2(IntPtr thisPtr, IntPtr parameter, byte* result); diff --git a/src/WinRT.Runtime/Projections/IDictionary.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IDictionary.netstandard2.0.cs index f9473aca1..016a1d4ef 100644 --- a/src/WinRT.Runtime/Projections/IDictionary.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IDictionary.netstandard2.0.cs @@ -15,6 +15,9 @@ namespace Windows.Foundation.Collections { [Guid("3C2925FE-8519-45C1-AA79-197B6718C1C1")] +#if EMBED + internal +#endif interface IMap : IIterable> { V Lookup(K key); @@ -33,7 +36,12 @@ namespace ABI.System.Collections.Generic using global::System.Runtime.CompilerServices; [Guid("3C2925FE-8519-45C1-AA79-197B6718C1C1")] - public class IDictionary : global::System.Collections.Generic.IDictionary +#if EMBED + internal +#else + public +#endif + class IDictionary : global::System.Collections.Generic.IDictionary { public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IDictionary obj) => obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IDictionary))); @@ -833,7 +841,12 @@ public unsafe uint Size public global::System.Collections.Generic.IEnumerator> GetEnumerator() => _FromMap.GetEnumerator(); IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); } - public static class IDictionary_Delegates +#if EMBED + internal +#else + public +#endif + static class IDictionary_Delegates { public unsafe delegate int GetView_3(IntPtr thisPtr, out IntPtr __return_value__); public unsafe delegate int Clear_6(IntPtr thisPtr); diff --git a/src/WinRT.Runtime/Projections/IDisposable.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IDisposable.netstandard2.0.cs index b2990e57f..c31716c17 100644 --- a/src/WinRT.Runtime/Projections/IDisposable.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IDisposable.netstandard2.0.cs @@ -8,7 +8,12 @@ namespace ABI.System { [global::WinRT.ObjectReferenceWrapper(nameof(_obj)), EditorBrowsable(EditorBrowsableState.Never)] [Guid("30D5A829-7FA4-4026-83BB-D75BAE4EA99E")] - public unsafe class IDisposable : global::System.IDisposable +#if EMBED + internal +#else + public +#endif + unsafe class IDisposable : global::System.IDisposable { [Guid("30D5A829-7FA4-4026-83BB-D75BAE4EA99E")] public struct Vftbl diff --git a/src/WinRT.Runtime/Projections/IEnumerable.net5.cs b/src/WinRT.Runtime/Projections/IEnumerable.net5.cs index 2907ba377..c3d2b52e3 100644 --- a/src/WinRT.Runtime/Projections/IEnumerable.net5.cs +++ b/src/WinRT.Runtime/Projections/IEnumerable.net5.cs @@ -188,8 +188,13 @@ public static class IEnumerable_Delegates public unsafe delegate int First_0(IntPtr thisPtr, out IntPtr __return_value__); } - [Guid("6A79E863-4300-459A-9966-CBB660963EE1")] - public class IEnumerator : global::System.Collections.Generic.IEnumerator, global::Windows.Foundation.Collections.IIterator + [Guid("6A79E863-4300-459A-9966-CBB660963EE1")] +#if EMBED + internal +#else + public +#endif + class IEnumerator : global::System.Collections.Generic.IEnumerator, global::Windows.Foundation.Collections.IIterator { public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IEnumerator obj) => obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IEnumerator))); diff --git a/src/WinRT.Runtime/Projections/IEnumerable.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IEnumerable.netstandard2.0.cs index 880443695..5732026a4 100644 --- a/src/WinRT.Runtime/Projections/IEnumerable.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IEnumerable.netstandard2.0.cs @@ -38,8 +38,13 @@ namespace ABI.System.Collections.Generic using global::System; using global::System.Runtime.CompilerServices; - [Guid("FAA585EA-6214-4217-AFDA-7F46DE5869B3")] - public class IEnumerable : global::System.Collections.Generic.IEnumerable, global::Windows.Foundation.Collections.IIterable + [Guid("FAA585EA-6214-4217-AFDA-7F46DE5869B3")] +#if EMBED + internal +#else + public +#endif + class IEnumerable : global::System.Collections.Generic.IEnumerable, global::Windows.Foundation.Collections.IIterable { public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IEnumerable obj) => obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IEnumerable))); @@ -187,14 +192,24 @@ public IEnumerable(ObjectReference obj) public global::System.Collections.Generic.IEnumerator GetEnumerator() => _FromIterable.GetEnumerator(); IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - } - public static class IEnumerable_Delegates + } +#if EMBED + internal +#else + public +#endif + static class IEnumerable_Delegates { public unsafe delegate int First_0(IntPtr thisPtr, out IntPtr __return_value__); } - [Guid("6A79E863-4300-459A-9966-CBB660963EE1")] - public class IEnumerator : global::System.Collections.Generic.IEnumerator, global::Windows.Foundation.Collections.IIterator + [Guid("6A79E863-4300-459A-9966-CBB660963EE1")] +#if EMBED + internal +#else + public +#endif + class IEnumerator : global::System.Collections.Generic.IEnumerator, global::Windows.Foundation.Collections.IIterator { public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IEnumerator obj) => obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IEnumerator))); @@ -642,8 +657,13 @@ public unsafe bool HasCurrent public void Dispose() => _FromIterator.Dispose(); public T Current => _FromIterator.Current; object IEnumerator.Current => Current; - } - public static class IEnumerator_Delegates + } +#if EMBED + internal +#else + public +#endif + static class IEnumerator_Delegates { public unsafe delegate int MoveNext_2(IntPtr thisPtr, out byte __return_value__); public unsafe delegate int GetMany_3(IntPtr thisPtr, int __itemsSize, IntPtr items, out uint __return_value__); diff --git a/src/WinRT.Runtime/Projections/IList.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IList.netstandard2.0.cs index 8ca7e4d65..ebbe5368d 100644 --- a/src/WinRT.Runtime/Projections/IList.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IList.netstandard2.0.cs @@ -16,6 +16,9 @@ namespace Windows.Foundation.Collections { [Guid("913337E9-11A1-4345-A3A2-4E7F956E222D")] +#if EMBED + internal +#endif interface IVector : IIterable { T GetAt(uint index); @@ -39,7 +42,12 @@ namespace ABI.System.Collections.Generic using global::System.Runtime.CompilerServices; [Guid("913337E9-11A1-4345-A3A2-4E7F956E222D")] - public class IList : global::System.Collections.Generic.IList +#if EMBED + internal +#else + public +#endif + class IList : global::System.Collections.Generic.IList { public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IList obj) => obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IList))); @@ -921,7 +929,13 @@ public unsafe uint Size public global::System.Collections.Generic.IEnumerator GetEnumerator() => _FromVector.GetEnumerator(); IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); } - public static class IList_Delegates + +#if EMBED + internal +#else + public +#endif + static class IList_Delegates { public unsafe delegate int GetView_2(IntPtr thisPtr, out IntPtr __return_value__); public unsafe delegate int RemoveAt_6(IntPtr thisPtr, uint index); diff --git a/src/WinRT.Runtime/Projections/INotifyCollectionChanged.net5.cs b/src/WinRT.Runtime/Projections/INotifyCollectionChanged.net5.cs index 7e66df4ed..20bb637f0 100644 --- a/src/WinRT.Runtime/Projections/INotifyCollectionChanged.net5.cs +++ b/src/WinRT.Runtime/Projections/INotifyCollectionChanged.net5.cs @@ -10,8 +10,13 @@ namespace ABI.System.Collections.Specialized { [DynamicInterfaceCastableImplementation] [EditorBrowsable(EditorBrowsableState.Never)] - [Guid("530155E1-28A5-5693-87CE-30724D95A06D")] - public unsafe interface INotifyCollectionChanged : global::System.Collections.Specialized.INotifyCollectionChanged + [Guid("530155E1-28A5-5693-87CE-30724D95A06D")] +#if EMBED + internal +#else + public +#endif + unsafe interface INotifyCollectionChanged : global::System.Collections.Specialized.INotifyCollectionChanged { [Guid("530155E1-28A5-5693-87CE-30724D95A06D")] public struct Vftbl diff --git a/src/WinRT.Runtime/Projections/INotifyCollectionChanged.netstandard2.0.cs b/src/WinRT.Runtime/Projections/INotifyCollectionChanged.netstandard2.0.cs index 2c30e2f72..3cf895b56 100644 --- a/src/WinRT.Runtime/Projections/INotifyCollectionChanged.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/INotifyCollectionChanged.netstandard2.0.cs @@ -10,7 +10,12 @@ namespace ABI.System.Collections.Specialized { [global::WinRT.ObjectReferenceWrapper(nameof(_obj)), EditorBrowsable(EditorBrowsableState.Never)] [Guid("530155E1-28A5-5693-87CE-30724D95A06D")] - public unsafe class INotifyCollectionChanged : global::System.Collections.Specialized.INotifyCollectionChanged +#if EMBED + internal +#else + public +#endif + unsafe class INotifyCollectionChanged : global::System.Collections.Specialized.INotifyCollectionChanged { [Guid("530155E1-28A5-5693-87CE-30724D95A06D")] public struct Vftbl diff --git a/src/WinRT.Runtime/Projections/INotifyDataErrorInfo.net5.cs b/src/WinRT.Runtime/Projections/INotifyDataErrorInfo.net5.cs index 34aa4a170..5d5cb3884 100644 --- a/src/WinRT.Runtime/Projections/INotifyDataErrorInfo.net5.cs +++ b/src/WinRT.Runtime/Projections/INotifyDataErrorInfo.net5.cs @@ -12,7 +12,12 @@ namespace ABI.System.ComponentModel [DynamicInterfaceCastableImplementation] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [Guid("0EE6C2CC-273E-567D-BC0A-1DD87EE51EBA")] - public unsafe interface INotifyDataErrorInfo : global::System.ComponentModel.INotifyDataErrorInfo +#if EMBED + internal +#else + public +#endif + unsafe interface INotifyDataErrorInfo : global::System.ComponentModel.INotifyDataErrorInfo { [Guid("0EE6C2CC-273E-567D-BC0A-1DD87EE51EBA")] public struct Vftbl diff --git a/src/WinRT.Runtime/Projections/INotifyDataErrorInfo.netstandard2.0.cs b/src/WinRT.Runtime/Projections/INotifyDataErrorInfo.netstandard2.0.cs index 296275a90..691027f69 100644 --- a/src/WinRT.Runtime/Projections/INotifyDataErrorInfo.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/INotifyDataErrorInfo.netstandard2.0.cs @@ -11,13 +11,18 @@ namespace ABI.System.ComponentModel { [global::WinRT.ObjectReferenceWrapper(nameof(_obj)), global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [Guid("0EE6C2CC-273E-567D-BC0A-1DD87EE51EBA")] - public unsafe class INotifyDataErrorInfo : global::System.ComponentModel.INotifyDataErrorInfo +#if EMBED + internal +#else + public +#endif + unsafe class INotifyDataErrorInfo : global::System.ComponentModel.INotifyDataErrorInfo { [Guid("0EE6C2CC-273E-567D-BC0A-1DD87EE51EBA")] public struct Vftbl { internal IInspectable.Vftbl IInspectableVftbl; -#if NETSTANDARD2_0 +#if !NET private void* _get_HasErrors_0; public delegate* unmanaged[Stdcall] get_HasErrors_0 { get => (delegate* unmanaged[Stdcall])_get_HasErrors_0; set => _get_HasErrors_0 = (void*)value; } private void* _add_ErrorsChanged_1; @@ -35,7 +40,7 @@ public struct Vftbl public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 +#if !NET private static Delegate[] DelegateCache = new Delegate[4]; #endif @@ -45,7 +50,7 @@ static unsafe Vftbl() (*(Vftbl*)AbiToProjectionVftablePtr) = new Vftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 +#if !NET _get_HasErrors_0 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new INotifyDataErrorInfo_Delegates.get_HasErrors_0(Do_Abi_get_HasErrors_0)).ToPointer(), _add_ErrorsChanged_1 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new INotifyDataErrorInfo_Delegates.add_ErrorsChanged_1(Do_Abi_add_ErrorsChanged_1)).ToPointer(), _remove_ErrorsChanged_2 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[2] = new INotifyDataErrorInfo_Delegates.remove_ErrorsChanged_2(Do_Abi_remove_ErrorsChanged_2)).ToPointer(), @@ -59,7 +64,7 @@ static unsafe Vftbl() }; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private static unsafe int Do_Abi_GetErrors_3(IntPtr thisPtr, IntPtr propertyName, IntPtr* result) @@ -82,7 +87,7 @@ private static unsafe int Do_Abi_GetErrors_3(IntPtr thisPtr, IntPtr propertyName return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private static unsafe int Do_Abi_get_HasErrors_0(IntPtr thisPtr, byte* value) @@ -107,7 +112,7 @@ private static unsafe int Do_Abi_get_HasErrors_0(IntPtr thisPtr, byte* value) private readonly static Lazy>>> _ErrorsChanged_TokenTablesLazy = new(); private static global::System.Runtime.CompilerServices.ConditionalWeakTable>> _ErrorsChanged_TokenTables => _ErrorsChanged_TokenTablesLazy.Value; -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new [] {typeof(CallConvStdcall)})] #endif private static unsafe int Do_Abi_add_ErrorsChanged_1(IntPtr thisPtr, IntPtr handler, global::WinRT.EventRegistrationToken* token) @@ -127,7 +132,7 @@ private static unsafe int Do_Abi_add_ErrorsChanged_1(IntPtr thisPtr, IntPtr hand } } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new [] {typeof(CallConvStdcall)})] #endif private static unsafe int Do_Abi_remove_ErrorsChanged_2(IntPtr thisPtr, global::WinRT.EventRegistrationToken token) diff --git a/src/WinRT.Runtime/Projections/INotifyPropertyChanged.netstandard2.0.cs b/src/WinRT.Runtime/Projections/INotifyPropertyChanged.netstandard2.0.cs index 9f2274aef..51e224064 100644 --- a/src/WinRT.Runtime/Projections/INotifyPropertyChanged.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/INotifyPropertyChanged.netstandard2.0.cs @@ -9,7 +9,12 @@ namespace ABI.System.ComponentModel { [global::WinRT.ObjectReferenceWrapper(nameof(_obj)), global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [Guid("90B17601-B065-586E-83D9-9ADC3A695284")] - public unsafe class INotifyPropertyChanged : global::System.ComponentModel.INotifyPropertyChanged +#if EMBED + internal +#else + public +#endif + unsafe class INotifyPropertyChanged : global::System.ComponentModel.INotifyPropertyChanged { [Guid("90B17601-B065-586E-83D9-9ADC3A695284")] [StructLayout(LayoutKind.Sequential)] diff --git a/src/WinRT.Runtime/Projections/IPropertyValue.net5.cs b/src/WinRT.Runtime/Projections/IPropertyValue.net5.cs index 7d85ae988..a462bc323 100644 --- a/src/WinRT.Runtime/Projections/IPropertyValue.net5.cs +++ b/src/WinRT.Runtime/Projections/IPropertyValue.net5.cs @@ -1207,15 +1207,15 @@ private static unsafe int Do_Abi_get_Type_0(IntPtr thisPtr, global::Windows.Foun { value = global::Windows.Foundation.PropertyType.Guid; } - else if (string.CompareOrdinal(managedType.FullName, "Windows.Foundation.Point") == 0) + else if (managedType.FullName == "Windows.Foundation.Point") { value = global::Windows.Foundation.PropertyType.Point; } - else if (string.CompareOrdinal(managedType.FullName, "Windows.Foundation.Rect") == 0) + else if (managedType.FullName == "Windows.Foundation.Rect") { value = global::Windows.Foundation.PropertyType.Rect; } - else if (string.CompareOrdinal(managedType.FullName, "Windows.Foundation.Size") == 0) + else if (managedType.FullName == "Windows.Foundation.Size") { value = global::Windows.Foundation.PropertyType.Size; } diff --git a/src/WinRT.Runtime/Projections/IPropertyValue.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IPropertyValue.netstandard2.0.cs index 97cb7de4f..6f47ffae8 100644 --- a/src/WinRT.Runtime/Projections/IPropertyValue.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IPropertyValue.netstandard2.0.cs @@ -1131,15 +1131,15 @@ private static unsafe int Do_Abi_get_Type_0(IntPtr thisPtr, global::Windows.Foun { value = global::Windows.Foundation.PropertyType.Guid; } - else if (string.CompareOrdinal(managedType.FullName, "Windows.Foundation.Point") == 0) + else if (managedType.FullName == "Windows.Foundation.Point") { value = global::Windows.Foundation.PropertyType.Point; } - else if (string.CompareOrdinal(managedType.FullName, "Windows.Foundation.Rect") == 0) + else if (managedType.FullName == "Windows.Foundation.Rect") { value = global::Windows.Foundation.PropertyType.Rect; } - else if (string.CompareOrdinal(managedType.FullName, "Windows.Foundation.Size") == 0) + else if (managedType.FullName == "Windows.Foundation.Size") { value = global::Windows.Foundation.PropertyType.Size; } diff --git a/src/WinRT.Runtime/Projections/IReadOnlyDictionary.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IReadOnlyDictionary.netstandard2.0.cs index ad8d981d5..d96914c71 100644 --- a/src/WinRT.Runtime/Projections/IReadOnlyDictionary.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IReadOnlyDictionary.netstandard2.0.cs @@ -15,6 +15,9 @@ namespace Windows.Foundation.Collections { [Guid("E480CE40-A338-4ADA-ADCF-272272E48CB9")] +#if EMBED + internal +#endif interface IMapView : IIterable> { V Lookup(K key); @@ -30,7 +33,12 @@ namespace ABI.System.Collections.Generic using global::System.Runtime.CompilerServices; [Guid("E480CE40-A338-4ADA-ADCF-272272E48CB9")] - public class IReadOnlyDictionary : global::System.Collections.Generic.IReadOnlyDictionary +#if EMBED + internal +#else + public +#endif + class IReadOnlyDictionary : global::System.Collections.Generic.IReadOnlyDictionary { public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IReadOnlyDictionary obj) => obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IReadOnlyDictionary))); @@ -723,7 +731,13 @@ public unsafe uint Size public global::System.Collections.Generic.IEnumerator> GetEnumerator() => _FromMapView.GetEnumerator(); IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); } - public static class IReadOnlyDictionary_Delegates + +#if EMBED + internal +#else + public +#endif + static class IReadOnlyDictionary_Delegates { public unsafe delegate int Split_3(IntPtr thisPtr, out IntPtr first, out IntPtr second); } diff --git a/src/WinRT.Runtime/Projections/IReadOnlyList.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IReadOnlyList.netstandard2.0.cs index da9c355b0..900c57b6b 100644 --- a/src/WinRT.Runtime/Projections/IReadOnlyList.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IReadOnlyList.netstandard2.0.cs @@ -15,6 +15,9 @@ namespace Windows.Foundation.Collections { [Guid("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56")] +#if EMBED + internal +#endif interface IVectorView : IIterable { T GetAt(uint index); @@ -30,7 +33,12 @@ namespace ABI.System.Collections.Generic using global::System.Runtime.CompilerServices; [Guid("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56")] - public class IReadOnlyList : global::System.Collections.Generic.IReadOnlyList +#if EMBED + internal +#else + public +#endif + class IReadOnlyList : global::System.Collections.Generic.IReadOnlyList { public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IReadOnlyList obj) => obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IReadOnlyList))); @@ -435,7 +443,12 @@ public unsafe uint Size IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); } - public static class IReadOnlyList_Delegates +#if EMBED + internal +#else + public +#endif + static class IReadOnlyList_Delegates { public unsafe delegate int GetMany_3(IntPtr thisPtr, uint startIndex, int __itemsSize, IntPtr items, out uint __return_value__); } diff --git a/src/WinRT.Runtime/Projections/IReferenceArray.net5.cs b/src/WinRT.Runtime/Projections/IReferenceArray.net5.cs index e8d212265..ccddfd163 100644 --- a/src/WinRT.Runtime/Projections/IReferenceArray.net5.cs +++ b/src/WinRT.Runtime/Projections/IReferenceArray.net5.cs @@ -100,7 +100,7 @@ public static IntPtr FromManaged(object value) } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } + public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IReferenceArray)); diff --git a/src/WinRT.Runtime/Projections/IReferenceArray.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IReferenceArray.netstandard2.0.cs index 2f6012a45..710e3f6f0 100644 --- a/src/WinRT.Runtime/Projections/IReferenceArray.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IReferenceArray.netstandard2.0.cs @@ -100,7 +100,7 @@ public static IntPtr FromManaged(object value) } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } + public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IReferenceArray)); diff --git a/src/WinRT.Runtime/Projections/IServiceProvider.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IServiceProvider.netstandard2.0.cs index 18af3ec5b..b650dbc85 100644 --- a/src/WinRT.Runtime/Projections/IServiceProvider.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IServiceProvider.netstandard2.0.cs @@ -11,7 +11,12 @@ namespace ABI.System { [global::WinRT.ObjectReferenceWrapper(nameof(_obj)), global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [Guid("68B3A2DF-8173-539F-B524-C8A2348F5AFB")] - public unsafe class IServiceProvider : global::System.IServiceProvider +#if EMBED + internal +#else + public +#endif + unsafe class IServiceProvider : global::System.IServiceProvider { [Guid("68B3A2DF-8173-539F-B524-C8A2348F5AFB")] public struct Vftbl diff --git a/src/WinRT.Runtime/Projections/IStringable.cs b/src/WinRT.Runtime/Projections/IStringable.cs index 95921f065..608a2bef0 100644 --- a/src/WinRT.Runtime/Projections/IStringable.cs +++ b/src/WinRT.Runtime/Projections/IStringable.cs @@ -18,7 +18,7 @@ internal unsafe struct ManagedIStringableVftbl private static readonly ManagedIStringableVftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 +#if !NET private unsafe delegate int ToStringDelegate(IntPtr thisPtr, IntPtr* value); private static readonly ToStringDelegate delegateCache; #endif @@ -27,7 +27,7 @@ static unsafe ManagedIStringableVftbl() AbiToProjectionVftable = new ManagedIStringableVftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 +#if !NET _ToString_0 = Marshal.GetFunctionPointerForDelegate(delegateCache = Do_Abi_ToString_0).ToPointer() #else _ToString_0 = (delegate* unmanaged)&Do_Abi_ToString_0 @@ -38,7 +38,7 @@ static unsafe ManagedIStringableVftbl() AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly] #endif private static unsafe int Do_Abi_ToString_0(IntPtr thisPtr, IntPtr* value) diff --git a/src/WinRT.Runtime/Projections/KeyValuePair.cs b/src/WinRT.Runtime/Projections/KeyValuePair.cs index 3ef477c28..7d387ef3e 100644 --- a/src/WinRT.Runtime/Projections/KeyValuePair.cs +++ b/src/WinRT.Runtime/Projections/KeyValuePair.cs @@ -27,8 +27,13 @@ namespace ABI.System.Collections.Generic { using global::System; - [Guid("02B51929-C1C4-4A7E-8940-0312B5C18500")] - public class KeyValuePair : global::Windows.Foundation.Collections.IKeyValuePair + [Guid("02B51929-C1C4-4A7E-8940-0312B5C18500")] +#if EMBED + internal +#else + public +#endif + class KeyValuePair : global::Windows.Foundation.Collections.IKeyValuePair { public static IObjectReference CreateMarshaler(global::System.Collections.Generic.KeyValuePair obj) => MarshalInterface>.CreateMarshaler(obj); diff --git a/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs b/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs index d3c5d22f0..56f26a5f6 100644 --- a/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs +++ b/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs @@ -165,7 +165,12 @@ namespace ABI.System.Collections.Specialized { [EditorBrowsable(EditorBrowsableState.Never)] [StructLayout(LayoutKind.Sequential)] - public struct NotifyCollectionChangedEventArgs +#if EMBED + internal +#else + public +#endif + struct NotifyCollectionChangedEventArgs { private static WeakLazy _propertyChangedArgsFactory = new WeakLazy(); @@ -232,7 +237,7 @@ public static IntPtr FromManaged(global::System.Collections.Specialized.NotifyCo } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } + public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } public static string GetGuidSignature() { diff --git a/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs b/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs index ffdb57a16..3afcde5f2 100644 --- a/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs +++ b/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using WinRT; @@ -12,9 +12,14 @@ namespace ABI.System.Collections.Specialized [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [Guid("8B0909DC-2005-5D93-BF8A-725F017BAA8D")] - public static class NotifyCollectionChangedEventHandler - { -#if NETSTANDARD2_0 +#if EMBED + internal +#else + public +#endif + static class NotifyCollectionChangedEventHandler + { +#if !NET private unsafe delegate int Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e); #endif @@ -25,8 +30,8 @@ static unsafe NotifyCollectionChangedEventHandler() { AbiToProjectionVftable = new global::WinRT.Interop.IDelegateVftbl { - IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, -#if NETSTANDARD2_0 + IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, +#if !NET Invoke = Marshal.GetFunctionPointerForDelegate(AbiInvokeDelegate = (Abi_Invoke)Do_Abi_Invoke) #else Invoke = (IntPtr)(delegate* unmanaged[Stdcall])&Do_Abi_Invoke @@ -45,13 +50,13 @@ public static unsafe IObjectReference CreateMarshaler(global::System.Collections public static IntPtr GetAbi(IObjectReference value) => MarshalInterfaceHelper.GetAbi(value); public static unsafe global::System.Collections.Specialized.NotifyCollectionChangedEventHandler FromAbi(IntPtr nativeDelegate) - { + { var abiDelegate = ComWrappersSupport.GetObjectReferenceForInterface(nativeDelegate)?.As(GuidGenerator.GetIID(typeof(NotifyCollectionChangedEventHandler))); return abiDelegate is null ? null : (global::System.Collections.Specialized.NotifyCollectionChangedEventHandler)ComWrappersSupport.TryRegisterObjectForInterface(new global::System.Collections.Specialized.NotifyCollectionChangedEventHandler(new NativeDelegateWrapper(abiDelegate).Invoke), nativeDelegate); } [global::WinRT.ObjectReferenceWrapper(nameof(_nativeDelegate))] -#if NETSTANDARD2_0 +#if !NET private class NativeDelegateWrapper #else private class NativeDelegateWrapper : IWinRTObject @@ -64,19 +69,17 @@ public NativeDelegateWrapper(ObjectReference _nativeDelegate; bool IWinRTObject.HasUnwrappableNativeObject => true; - private Lazy> _lazyQueryInterfaceCache = new(); - ConcurrentDictionary IWinRTObject.QueryInterfaceCache => _lazyQueryInterfaceCache.Value; - private Lazy> _lazyAdditionalTypeData = new(); - ConcurrentDictionary IWinRTObject.AdditionalTypeData => _lazyAdditionalTypeData.Value; + ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); + ConcurrentDictionary IWinRTObject.AdditionalTypeData { get; } = new(); #endif public unsafe void Invoke(object sender, global::System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { - IntPtr ThisPtr = _nativeDelegate.ThisPtr; -#if NETSTANDARD2_0 + IntPtr ThisPtr = _nativeDelegate.ThisPtr; +#if !NET var abiInvoke = Marshal.GetDelegateForFunctionPointer(_nativeDelegate.Vftbl.Invoke); #else var abiInvoke = (delegate* unmanaged[Stdcall])(_nativeDelegate.Vftbl.Invoke); @@ -103,9 +106,9 @@ public static IntPtr FromManaged(global::System.Collections.Specialized.NotifyCo public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper.DisposeMarshaler(value); - public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper.DisposeAbi(abi); - -#if !NETSTANDARD2_0 + public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper.DisposeAbi(abi); + +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static unsafe int Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e) @@ -124,8 +127,8 @@ private static unsafe int Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e) } return 0; } - } - + } + internal sealed unsafe class NotifyCollectionChangedEventSource : EventSource { internal NotifyCollectionChangedEventSource(IObjectReference obj, @@ -142,29 +145,29 @@ protected override void DisposeMarshaler(IObjectReference marshaler) => NotifyCollectionChangedEventHandler.DisposeMarshaler(marshaler); protected override IntPtr GetAbi(IObjectReference marshaler) => - marshaler is null ? IntPtr.Zero : NotifyCollectionChangedEventHandler.GetAbi(marshaler); - - protected override State CreateEventState() => - new EventState(_obj.ThisPtr, _index); - - private sealed class EventState : State - { - public EventState(IntPtr obj, int index) - : base(obj, index) - { - } - - protected override Delegate GetEventInvoke() - { - global::System.Collections.Specialized.NotifyCollectionChangedEventHandler handler = - (global::System.Object obj, global::System.Collections.Specialized.NotifyCollectionChangedEventArgs e) => - { - var localDel = del; - if (localDel != null) - localDel.Invoke(obj, e); - }; - return handler; - } + marshaler is null ? IntPtr.Zero : NotifyCollectionChangedEventHandler.GetAbi(marshaler); + + protected override State CreateEventState() => + new EventState(_obj.ThisPtr, _index); + + private sealed class EventState : State + { + public EventState(IntPtr obj, int index) + : base(obj, index) + { + } + + protected override Delegate GetEventInvoke() + { + global::System.Collections.Specialized.NotifyCollectionChangedEventHandler handler = + (global::System.Object obj, global::System.Collections.Specialized.NotifyCollectionChangedEventArgs e) => + { + var localDel = del; + if (localDel != null) + localDel.Invoke(obj, e); + }; + return handler; + } } } } diff --git a/src/WinRT.Runtime/Projections/Nullable.cs b/src/WinRT.Runtime/Projections/Nullable.cs index 1397db33b..bdd334a42 100644 --- a/src/WinRT.Runtime/Projections/Nullable.cs +++ b/src/WinRT.Runtime/Projections/Nullable.cs @@ -55,7 +55,12 @@ namespace ABI.System { [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] [Guid("61C17706-2D65-11E0-9AE8-D48564015472")] - public class Nullable +#if EMBED + internal +#else + public +#endif + class Nullable { public static IObjectReference CreateMarshaler(object value) { @@ -95,7 +100,7 @@ public static IntPtr FromManaged(object value) } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } + public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(Nullable)); diff --git a/src/WinRT.Runtime/Projections/PropertyChangedEventArgs.cs b/src/WinRT.Runtime/Projections/PropertyChangedEventArgs.cs index b14658da0..3b14adf7d 100644 --- a/src/WinRT.Runtime/Projections/PropertyChangedEventArgs.cs +++ b/src/WinRT.Runtime/Projections/PropertyChangedEventArgs.cs @@ -73,7 +73,12 @@ namespace ABI.System.ComponentModel { [EditorBrowsable(EditorBrowsableState.Never)] [StructLayout(LayoutKind.Sequential)] - public unsafe struct PropertyChangedEventArgs +#if EMBED + internal +#else + public +#endif + unsafe struct PropertyChangedEventArgs { private static WeakLazy _propertyChangedArgsFactory = new WeakLazy(); @@ -133,7 +138,7 @@ public static IntPtr FromManaged(global::System.ComponentModel.PropertyChangedEv } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } + public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } public static string GetGuidSignature() { diff --git a/src/WinRT.Runtime/Projections/PropertyChangedEventHandler.cs b/src/WinRT.Runtime/Projections/PropertyChangedEventHandler.cs index 2e454556f..c06a8efd3 100644 --- a/src/WinRT.Runtime/Projections/PropertyChangedEventHandler.cs +++ b/src/WinRT.Runtime/Projections/PropertyChangedEventHandler.cs @@ -11,9 +11,14 @@ namespace ABI.System.ComponentModel { [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [Guid("E3DE52F6-1E32-5DA6-BB2D-B5B6096C962D")] - public static class PropertyChangedEventHandler - { -#if NETSTANDARD2_0 +#if EMBED + internal +#else + public +#endif + static class PropertyChangedEventHandler + { +#if !NET private unsafe delegate int Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e); #endif @@ -24,8 +29,8 @@ static unsafe PropertyChangedEventHandler() { AbiToProjectionVftable = new global::WinRT.Interop.IDelegateVftbl { - IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, -#if NETSTANDARD2_0 + IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, +#if !NET Invoke = Marshal.GetFunctionPointerForDelegate(AbiInvokeDelegate = (Abi_Invoke)Do_Abi_Invoke) #else Invoke = (IntPtr)(delegate* unmanaged[Stdcall])&Do_Abi_Invoke @@ -44,13 +49,13 @@ public static unsafe IObjectReference CreateMarshaler(global::System.ComponentMo public static IntPtr GetAbi(IObjectReference value) => MarshalInterfaceHelper.GetAbi(value); public static unsafe global::System.ComponentModel.PropertyChangedEventHandler FromAbi(IntPtr nativeDelegate) - { + { var abiDelegate = ComWrappersSupport.GetObjectReferenceForInterface(nativeDelegate)?.As(GuidGenerator.GetIID(typeof(PropertyChangedEventHandler))); return abiDelegate is null ? null : (global::System.ComponentModel.PropertyChangedEventHandler)ComWrappersSupport.TryRegisterObjectForInterface(new global::System.ComponentModel.PropertyChangedEventHandler(new NativeDelegateWrapper(abiDelegate).Invoke), nativeDelegate); } [global::WinRT.ObjectReferenceWrapper(nameof(_nativeDelegate))] -#if NETSTANDARD2_0 +#if !NET private class NativeDelegateWrapper #else private class NativeDelegateWrapper : IWinRTObject @@ -63,19 +68,17 @@ public NativeDelegateWrapper(ObjectReference _nativeDelegate; bool IWinRTObject.HasUnwrappableNativeObject => true; - private Lazy> _lazyQueryInterfaceCache = new(); - ConcurrentDictionary IWinRTObject.QueryInterfaceCache => _lazyQueryInterfaceCache.Value; - private Lazy> _lazyAdditionalTypeData = new(); - ConcurrentDictionary IWinRTObject.AdditionalTypeData => _lazyAdditionalTypeData.Value; + ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); + ConcurrentDictionary IWinRTObject.AdditionalTypeData { get; } = new(); #endif public unsafe void Invoke(object sender, global::System.ComponentModel.PropertyChangedEventArgs e) - { - IntPtr ThisPtr = _nativeDelegate.ThisPtr; -#if NETSTANDARD2_0 + { + IntPtr ThisPtr = _nativeDelegate.ThisPtr; +#if !NET var abiInvoke = Marshal.GetDelegateForFunctionPointer(_nativeDelegate.Vftbl.Invoke); #else var abiInvoke = (delegate* unmanaged[Stdcall])(_nativeDelegate.Vftbl.Invoke); @@ -102,9 +105,9 @@ public static IntPtr FromManaged(global::System.ComponentModel.PropertyChangedEv public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper.DisposeMarshaler(value); - public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper.DisposeAbi(abi); - -#if !NETSTANDARD2_0 + public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper.DisposeAbi(abi); + +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static unsafe int Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e) @@ -123,8 +126,8 @@ private static unsafe int Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e) } return 0; } - } - + } + internal sealed unsafe class PropertyChangedEventSource : EventSource { internal PropertyChangedEventSource(IObjectReference obj, @@ -141,29 +144,29 @@ protected override void DisposeMarshaler(IObjectReference marshaler) => PropertyChangedEventHandler.DisposeMarshaler(marshaler); protected override IntPtr GetAbi(IObjectReference marshaler) => - marshaler is null ? IntPtr.Zero : PropertyChangedEventHandler.GetAbi(marshaler); - - protected override State CreateEventState() => - new EventState(_obj.ThisPtr, _index); - - private sealed class EventState : State - { - public EventState(IntPtr obj, int index) - : base(obj, index) - { - } - - protected override Delegate GetEventInvoke() - { - global::System.ComponentModel.PropertyChangedEventHandler handler = - (global::System.Object obj, global::System.ComponentModel.PropertyChangedEventArgs e) => - { - var localDel = del; - if (localDel != null) - localDel.Invoke(obj, e); - }; - return handler; - } + marshaler is null ? IntPtr.Zero : PropertyChangedEventHandler.GetAbi(marshaler); + + protected override State CreateEventState() => + new EventState(_obj.ThisPtr, _index); + + private sealed class EventState : State + { + public EventState(IntPtr obj, int index) + : base(obj, index) + { + } + + protected override Delegate GetEventInvoke() + { + global::System.ComponentModel.PropertyChangedEventHandler handler = + (global::System.Object obj, global::System.ComponentModel.PropertyChangedEventArgs e) => + { + var localDel = del; + if (localDel != null) + localDel.Invoke(obj, e); + }; + return handler; + } } } } diff --git a/src/WinRT.Runtime/Projections/Uri.cs b/src/WinRT.Runtime/Projections/Uri.cs index 7043561f5..6234774e3 100644 --- a/src/WinRT.Runtime/Projections/Uri.cs +++ b/src/WinRT.Runtime/Projections/Uri.cs @@ -81,7 +81,12 @@ public unsafe IObjectReference CreateUri(string uri) [StructLayout(LayoutKind.Sequential)] - public unsafe struct Uri +#if EMBED + internal +#else + public +#endif + unsafe struct Uri { private static WeakLazy _uriActivationFactory = new WeakLazy(); @@ -141,7 +146,7 @@ public static IntPtr FromManaged(global::System.Uri value) } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } + public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } public static string GetGuidSignature() { diff --git a/src/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs b/src/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs index d9372098b..3c8c9ae05 100644 --- a/src/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs +++ b/src/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs @@ -5,7 +5,12 @@ namespace WinRT { - public class SingleInterfaceOptimizedObject : IWinRTObject, IDynamicInterfaceCastable +#if EMBED + internal +#else + public +#endif + class SingleInterfaceOptimizedObject : IWinRTObject, IDynamicInterfaceCastable { private Type _type; private IObjectReference _obj; @@ -28,10 +33,8 @@ public SingleInterfaceOptimizedObject(Type type, IObjectReference objRef) IObjectReference IWinRTObject.NativeObject => _obj; bool IWinRTObject.HasUnwrappableNativeObject => false; - private Lazy> _lazyQueryInterfaceCache = new(); - ConcurrentDictionary IWinRTObject.QueryInterfaceCache => _lazyQueryInterfaceCache.Value; - private Lazy> _lazyAdditionalTypeData = new(); - ConcurrentDictionary IWinRTObject.AdditionalTypeData => _lazyAdditionalTypeData.Value; + ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); + ConcurrentDictionary IWinRTObject.AdditionalTypeData { get; } = new(); bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented) { diff --git a/src/WinRT.Runtime/TypeExtensions.cs b/src/WinRT.Runtime/TypeExtensions.cs index fd9eaddbb..4855fa030 100644 --- a/src/WinRT.Runtime/TypeExtensions.cs +++ b/src/WinRT.Runtime/TypeExtensions.cs @@ -4,33 +4,37 @@ namespace WinRT { - - public static class TypeExtensions +#if EMBED + internal +#else + public +#endif + static class TypeExtensions { private readonly static ConcurrentDictionary HelperTypeCache = new ConcurrentDictionary(); public static Type FindHelperType(this Type type) { return HelperTypeCache.GetOrAdd(type, (type) => - { - if (typeof(Exception).IsAssignableFrom(type)) - { - type = typeof(Exception); - } - Type customMapping = Projections.FindCustomHelperTypeMapping(type); - if (customMapping is object) - { - return customMapping; - } - - string fullTypeName = type.FullName; - string ccwTypePrefix = "ABI.Impl."; - if (fullTypeName.StartsWith(ccwTypePrefix, StringComparison.Ordinal)) - { - fullTypeName = fullTypeName.Substring(ccwTypePrefix.Length); - } - - var helper = $"ABI.{fullTypeName}"; + { + if (typeof(Exception).IsAssignableFrom(type)) + { + type = typeof(Exception); + } + Type customMapping = Projections.FindCustomHelperTypeMapping(type); + if (customMapping is object) + { + return customMapping; + } + + string fullTypeName = type.FullName; + string ccwTypePrefix = "ABI.Impl."; + if (fullTypeName.StartsWith(ccwTypePrefix)) + { + fullTypeName = fullTypeName.Substring(ccwTypePrefix.Length); + } + + var helper = $"ABI.{fullTypeName}"; return type.Assembly.GetType(helper) ?? Type.GetType(helper); }); } @@ -75,8 +79,8 @@ public static Type GetAbiType(this Type type) public static Type GetMarshalerType(this Type type) { return type.GetHelperType().GetMethod("CreateMarshaler", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).ReturnType; - } - + } + internal static Type GetMarshalerArrayType(this Type type) { return type.GetHelperType().GetMethod("CreateMarshalerArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)?.ReturnType; @@ -85,8 +89,8 @@ internal static Type GetMarshalerArrayType(this Type type) public static bool IsDelegate(this Type type) { return typeof(Delegate).IsAssignableFrom(type); - } - + } + internal static bool IsTypeOfType(this Type type) { return typeof(Type).IsAssignableFrom(type); @@ -94,11 +98,11 @@ internal static bool IsTypeOfType(this Type type) public static Type GetRuntimeClassCCWType(this Type type) { - return type.IsClass && !type.IsArray ? type.GetAuthoringMetadataType() : null; - } - - internal static Type GetAuthoringMetadataType(this Type type) - { + return type.IsClass && !type.IsArray ? type.GetAuthoringMetadataType() : null; + } + + internal static Type GetAuthoringMetadataType(this Type type) + { var ccwTypeName = $"ABI.Impl.{type.FullName}"; return type.Assembly.GetType(ccwTypeName, false) ?? Type.GetType(ccwTypeName, false); } diff --git a/src/WinRT.Runtime/TypeNameSupport.cs b/src/WinRT.Runtime/TypeNameSupport.cs index 7a73e671b..282a88e87 100644 --- a/src/WinRT.Runtime/TypeNameSupport.cs +++ b/src/WinRT.Runtime/TypeNameSupport.cs @@ -10,6 +10,9 @@ namespace WinRT { [Flags] +#if EMBED + internal +#endif enum TypeNameGenerationFlags { None = 0, @@ -23,10 +26,13 @@ enum TypeNameGenerationFlags NoCustomTypeName = 0x2 } +#if EMBED + internal +#endif static class TypeNameSupport { private static List projectionAssemblies = new List(); - private static ConcurrentDictionary typeNameCache = new ConcurrentDictionary(StringComparer.Ordinal) { ["TrackerCollection"] = null }; + private static ConcurrentDictionary typeNameCache = new ConcurrentDictionary() { ["TrackerCollection"] = null }; public static void RegisterProjectionAssembly(Assembly assembly) { @@ -39,21 +45,21 @@ public static void RegisterProjectionAssembly(Assembly assembly) /// The runtime class name to attempt to parse. /// The type, if found. Null otherwise public static Type FindTypeByNameCached(string runtimeClassName) - { + { return typeNameCache.GetOrAdd(runtimeClassName, (runtimeClassName) => { Type implementationType = null; - try - { - implementationType = FindTypeByName(runtimeClassName.AsSpan()).type; - } - catch (Exception) - { + try + { + implementationType = FindTypeByName(runtimeClassName.AsSpan()).type; } - return implementationType; + catch (Exception) + { + } + return implementationType; }); - } - + } + /// /// Parse the first full type name within the provided span. /// @@ -63,7 +69,7 @@ public static (Type type, int remaining) FindTypeByName(ReadOnlySpan runti { // Assume that anonymous types are expando objects, whether declared 'dynamic' or not. // It may be necessary to detect otherwise and return System.Object. - if(runtimeClassName.StartsWith("<>f__AnonymousType".AsSpan(), StringComparison.Ordinal)) + if(runtimeClassName.StartsWith("<>f__AnonymousType".AsSpan())) { return (typeof(System.Dynamic.ExpandoObject), 0); } @@ -163,7 +169,7 @@ public static Type ResolvePrimitiveType(string primitiveTypeName) /// Returns a tuple containing the simple type name of the type, and generic type parameters if they exist, and the index of the end of the type name in the span. private static (string genericTypeName, Type[] genericTypes, int remaining) ParseGenericTypeName(ReadOnlySpan partialTypeName) { - int possibleEndOfSimpleTypeName = partialTypeName.IndexOfAny(',', '>'); + int possibleEndOfSimpleTypeName = partialTypeName.IndexOfAny(new[] { ',', '>' }); int endOfSimpleTypeName = partialTypeName.Length; if (possibleEndOfSimpleTypeName != -1) { @@ -342,7 +348,7 @@ private static bool TryAppendWinRTInterfaceNameForType(Type type, StringBuilder private static bool TryAppendTypeName(Type type, StringBuilder builder, TypeNameGenerationFlags flags) { -#if NETSTANDARD2_0 +#if !NET // We can't easily determine from just the type // if the array is an "single dimension index from zero"-array in .NET Standard 2.0, // so just approximate it. diff --git a/src/WinRT.Runtime/WeakReference.netstandard2.0.cs b/src/WinRT.Runtime/WeakReference.netstandard2.0.cs index 37a0dc201..c2faf50fa 100644 --- a/src/WinRT.Runtime/WeakReference.netstandard2.0.cs +++ b/src/WinRT.Runtime/WeakReference.netstandard2.0.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WinRT.Interop; +using WinRT.Interop; namespace WinRT { @@ -10,7 +7,12 @@ namespace WinRT /// The lifetime of the weak reference is the lifetime of the native object instead of the C#/WinRT wrapper. /// /// The type of object the weak reference points to. - public sealed class WeakReference +#if EMBED + internal +#else + public +#endif + sealed class WeakReference where T : class { private System.WeakReference _managedWeakReference; From 490c33c9e043d4dff152c73b825213ce31827b4a Mon Sep 17 00:00:00 2001 From: Joshua Larkin <70237359+j0shuams@users.noreply.github.com> Date: Mon, 4 Oct 2021 11:13:20 -0700 Subject: [PATCH 02/11] merge master --- src/Authoring/WinRT.Host.Shim/Module.cs | 6 +- src/WinRT.Runtime/ComWrappersSupport.cs | 13 +- src/WinRT.Runtime/Context.cs | 2 +- src/WinRT.Runtime/IInspectable.net5.cs | 10 +- src/WinRT.Runtime/Marshalers.cs | 113 ++++++++++-------- src/WinRT.Runtime/Projections.cs | 4 +- .../Projections/DataErrorsChangedEventArgs.cs | 2 +- src/WinRT.Runtime/Projections/EventHandler.cs | 12 +- .../Projections/IPropertyValue.net5.cs | 6 +- .../IPropertyValue.netstandard2.0.cs | 6 +- .../Projections/IReferenceArray.net5.cs | 2 +- .../IReferenceArray.netstandard2.0.cs | 2 +- .../NotifyCollectionChangedEventArgs.cs | 2 +- .../NotifyCollectionChangedEventHandler.cs | 6 +- src/WinRT.Runtime/Projections/Nullable.cs | 2 +- .../Projections/PropertyChangedEventArgs.cs | 2 +- .../PropertyChangedEventHandler.cs | 6 +- src/WinRT.Runtime/Projections/Uri.cs | 2 +- .../SingleInterfaceOptimizedObject.net5.cs | 6 +- src/WinRT.Runtime/TypeExtensions.cs | 2 +- src/WinRT.Runtime/TypeNameSupport.cs | 6 +- 21 files changed, 119 insertions(+), 93 deletions(-) diff --git a/src/Authoring/WinRT.Host.Shim/Module.cs b/src/Authoring/WinRT.Host.Shim/Module.cs index ef439aad3..1e2a4039a 100644 --- a/src/Authoring/WinRT.Host.Shim/Module.cs +++ b/src/Authoring/WinRT.Host.Shim/Module.cs @@ -64,7 +64,7 @@ private static class ActivationLoader #else private class ActivationLoader : AssemblyLoadContext { - private static readonly ConcurrentDictionary ALCMapping = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary ALCMapping = new ConcurrentDictionary(StringComparer.Ordinal); private AssemblyDependencyResolver _resolver; public static Assembly LoadAssembly(string targetAssembly) @@ -79,7 +79,7 @@ private ActivationLoader(string path) AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext assemblyLoadContext, AssemblyName assemblyName) => { // Consolidate all WinRT.Runtime loads to the default ALC, or failing that, the first shim ALC - if (assemblyName.Name == "WinRT.Runtime") + if (string.CompareOrdinal(assemblyName.Name, "WinRT.Runtime") == 0) { string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); if (assemblyPath != null) @@ -93,7 +93,7 @@ private ActivationLoader(string path) protected override Assembly Load(AssemblyName assemblyName) { - if (assemblyName.Name != "WinRT.Runtime") + if (string.CompareOrdinal(assemblyName.Name, "WinRT.Runtime") != 0) { string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); if (assemblyPath != null) diff --git a/src/WinRT.Runtime/ComWrappersSupport.cs b/src/WinRT.Runtime/ComWrappersSupport.cs index dff5f564b..bae5651e6 100644 --- a/src/WinRT.Runtime/ComWrappersSupport.cs +++ b/src/WinRT.Runtime/ComWrappersSupport.cs @@ -25,7 +25,7 @@ namespace WinRT #endif static partial class ComWrappersSupport { - private readonly static ConcurrentDictionary> TypedObjectFactoryCache = new ConcurrentDictionary>(); + private readonly static ConcurrentDictionary> TypedObjectFactoryCache = new ConcurrentDictionary>(StringComparer.Ordinal); private readonly static ConditionalWeakTable CCWTable = new ConditionalWeakTable(); public static TReturn MarshalDelegateInvoke(IntPtr thisPtr, Func invoke) @@ -243,7 +243,7 @@ internal static (InspectableInfo inspectableInfo, List interf iids[i] = interfaceTableEntries[i].IID; } - if (type.FullName.StartsWith("ABI.")) + if (type.FullName.StartsWith("ABI.", StringComparison.Ordinal)) { type = Projections.FindCustomPublicTypeForAbiType(type) ?? type.Assembly.GetType(type.FullName.Substring("ABI.".Length)) ?? type; } @@ -260,7 +260,7 @@ private static bool IsNullableT(Type implementationType) private static bool IsIReferenceArray(Type implementationType) { - return implementationType.FullName.StartsWith("Windows.Foundation.IReferenceArray`1"); + return implementationType.FullName.StartsWith("Windows.Foundation.IReferenceArray`1", StringComparison.Ordinal); } private static Func CreateKeyValuePairFactory(Type type) @@ -316,16 +316,17 @@ private static Func CreateReferenceCachingFactory(Func CreateTypedRcwFactory(string runtimeClassName) { // If runtime class name is empty or "Object", then just use IInspectable. - if (string.IsNullOrEmpty(runtimeClassName) || runtimeClassName == "Object") + if (string.IsNullOrEmpty(runtimeClassName) || + string.CompareOrdinal(runtimeClassName, "Object") == 0) { return (IInspectable obj) => obj; } // PropertySet and ValueSet can return IReference but Nullable is illegal - if (runtimeClassName == "Windows.Foundation.IReference`1") + if (string.CompareOrdinal(runtimeClassName, "Windows.Foundation.IReference`1") == 0) { return CreateReferenceCachingFactory((IInspectable obj) => new ABI.System.Nullable(obj.ObjRef)); } - else if (runtimeClassName == "Windows.Foundation.IReference`1") + else if (string.CompareOrdinal(runtimeClassName, "Windows.Foundation.IReference`1") == 0) { return CreateReferenceCachingFactory((IInspectable obj) => new ABI.System.Nullable(obj.ObjRef)); } diff --git a/src/WinRT.Runtime/Context.cs b/src/WinRT.Runtime/Context.cs index a5d895e5a..7e67b37a1 100644 --- a/src/WinRT.Runtime/Context.cs +++ b/src/WinRT.Runtime/Context.cs @@ -63,7 +63,7 @@ public unsafe static void CallInContext(IntPtr contextCallbackPtr, IntPtr contex public static void DisposeContextCallback(IntPtr contextCallbackPtr) { - using var contextcallback = ObjectReference.Attach(ref contextCallbackPtr); + MarshalInspectable.DisposeAbi(contextCallbackPtr); } } } diff --git a/src/WinRT.Runtime/IInspectable.net5.cs b/src/WinRT.Runtime/IInspectable.net5.cs index 557a189c0..e6084b5de 100644 --- a/src/WinRT.Runtime/IInspectable.net5.cs +++ b/src/WinRT.Runtime/IInspectable.net5.cs @@ -11,10 +11,12 @@ namespace WinRT partial class IInspectable : IWinRTObject { IObjectReference IWinRTObject.NativeObject => _obj; - bool IWinRTObject.HasUnwrappableNativeObject => true; - - ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); - ConcurrentDictionary IWinRTObject.AdditionalTypeData { get; } = new(); + bool IWinRTObject.HasUnwrappableNativeObject => true; + + private Lazy> _lazyQueryInterfaceCache = new(); + ConcurrentDictionary IWinRTObject.QueryInterfaceCache => _lazyQueryInterfaceCache.Value; + private Lazy> _lazyAdditionalTypeData = new(); + ConcurrentDictionary IWinRTObject.AdditionalTypeData => _lazyAdditionalTypeData.Value; } } diff --git a/src/WinRT.Runtime/Marshalers.cs b/src/WinRT.Runtime/Marshalers.cs index 595dcc4b9..2b5ee8600 100644 --- a/src/WinRT.Runtime/Marshalers.cs +++ b/src/WinRT.Runtime/Marshalers.cs @@ -172,6 +172,10 @@ public static unsafe string[] FromAbiArray(object box) return null; } var abi = ((int length, IntPtr data))box; + if (abi.data == IntPtr.Zero) + { + return null; + } string[] array = new string[abi.length]; var data = (IntPtr*)abi.data.ToPointer(); for (int i = 0; i < abi.length; i++) @@ -280,7 +284,7 @@ struct MarshalBlittable { public struct MarshalerArray { - public MarshalerArray(Array array) => _gchandle = GCHandle.Alloc(array, GCHandleType.Pinned); + public MarshalerArray(Array array) => _gchandle = array is null ? default : GCHandle.Alloc(array, GCHandleType.Pinned); public void Dispose() => _gchandle.Dispose(); public GCHandle _gchandle; @@ -291,7 +295,7 @@ public struct MarshalerArray public static (int length, IntPtr data) GetAbiArray(object box) { var m = (MarshalerArray)box; - return (((Array)m._gchandle.Target).Length, m._gchandle.AddrOfPinnedObject()); + return m._gchandle.IsAllocated ? (((Array)m._gchandle.Target).Length, m._gchandle.AddrOfPinnedObject()) : (0, IntPtr.Zero); } public static unsafe T[] FromAbiArray(object box) @@ -301,6 +305,10 @@ public static unsafe T[] FromAbiArray(object box) return null; } var abi = ((int length, IntPtr data))box; + if (abi.data == IntPtr.Zero) + { + return null; + } var abiSpan = new ReadOnlySpan(abi.data.ToPointer(), abi.length); return abiSpan.ToArray(); } @@ -358,25 +366,8 @@ class MarshalGeneric protected static readonly Type MarshalerType = typeof(T).GetMarshalerType(); internal static readonly Type MarshalerArrayType = typeof(T).GetMarshalerArrayType(); - static MarshalGeneric() - { - CreateMarshaler = BindCreateMarshaler(); - GetAbi = BindGetAbi(); - FromAbi = BindFromAbi(); - CopyAbi = BindCopyAbi(); - FromManaged = BindFromManaged(); - CopyManaged = BindCopyManaged(); - DisposeMarshaler = BindDisposeMarshaler(); - DisposeAbi = BindDisposeAbi(); - CreateMarshalerArray = BindCreateMarshalerArray(); - GetAbiArray = BindGetAbiArray(); - FromAbiArray = BindFromAbiArray(); - FromManagedArray = BindFromManagedArray(); - DisposeMarshalerArray = BindDisposeMarshalerArray(); - DisposeAbiArray = BindDisposeAbiArray(); - } - - public static readonly Func CreateMarshaler; + public static readonly Func CreateMarshaler = (T value) => CreateMarshalerLazy.Value(value); + private static readonly Lazy> CreateMarshalerLazy = new(BindCreateMarshaler); private static Func BindCreateMarshaler() { var parms = new[] { Expression.Parameter(typeof(T), "arg") }; @@ -385,7 +376,8 @@ private static Func BindCreateMarshaler() typeof(object)), parms).Compile(); } - public static readonly Func GetAbi; + public static readonly Func GetAbi = (object objRef) => GetAbiLazy.Value(objRef); + private static readonly Lazy> GetAbiLazy = new(BindGetAbi); private static Func BindGetAbi() { var parms = new[] { Expression.Parameter(typeof(object), "arg") }; @@ -395,7 +387,8 @@ private static Func BindGetAbi() typeof(object)), parms).Compile(); } - public static readonly Action CopyAbi; + public static readonly Action CopyAbi = (object box, IntPtr dest) => CopyAbiLazy.Value(box, dest); + private static readonly Lazy> CopyAbiLazy = new(BindCopyAbi); private static Action BindCopyAbi() { var copyAbi = HelperType.GetMethod("CopyAbi", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -406,7 +399,8 @@ private static Action BindCopyAbi() new Expression[] { Expression.Convert(parms[0], MarshalerType), parms[1] }), parms).Compile(); } - public static readonly Func FromAbi; + public static readonly Func FromAbi = (object box) => FromAbiLazy.Value(box); + private static readonly Lazy> FromAbiLazy = new(BindFromAbi); private static Func BindFromAbi() { var parms = new[] { Expression.Parameter(typeof(object), "arg") }; @@ -415,7 +409,8 @@ private static Func BindFromAbi() new[] { Expression.Convert(parms[0], AbiType) }), parms).Compile(); } - public static readonly Func FromManaged; + public static readonly Func FromManaged = (T value) => FromManagedLazy.Value(value); + private static readonly Lazy> FromManagedLazy = new(BindFromManaged); private static Func BindFromManaged() { var parms = new[] { Expression.Parameter(typeof(T), "arg") }; @@ -424,7 +419,8 @@ private static Func BindFromManaged() typeof(object)), parms).Compile(); } - public static readonly Action CopyManaged; + public static readonly Action CopyManaged = (T value, IntPtr dest) => CopyManagedLazy.Value(value, dest); + private static readonly Lazy> CopyManagedLazy = new(BindCopyManaged); private static Action BindCopyManaged() { var copyManaged = HelperType.GetMethod("CopyManaged", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -434,7 +430,8 @@ private static Action BindCopyManaged() Expression.Call(copyManaged, parms), parms).Compile(); } - public static readonly Action DisposeMarshaler; + public static readonly Action DisposeMarshaler = (object objRef) => DisposeMarshalerLazy.Value(objRef); + private static readonly Lazy> DisposeMarshalerLazy = new(BindDisposeMarshaler); private static Action BindDisposeMarshaler() { var parms = new[] { Expression.Parameter(typeof(object), "arg") }; @@ -443,7 +440,8 @@ private static Action BindDisposeMarshaler() new[] { Expression.Convert(parms[0], MarshalerType) }), parms).Compile(); } - internal static readonly Action DisposeAbi; + internal static readonly Action DisposeAbi = (object box) => DisposeAbiLazy.Value(box); + private static readonly Lazy> DisposeAbiLazy = new(BindDisposeAbi); private static Action BindDisposeAbi() { var disposeAbi = HelperType.GetMethod("DisposeAbi", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -453,7 +451,8 @@ private static Action BindDisposeAbi() Expression.Call(disposeAbi, new[] { Expression.Convert(parms[0], AbiType) }), parms).Compile(); } - internal static readonly Func CreateMarshalerArray; + internal static readonly Func CreateMarshalerArray = (T[] array) => CreateMarshalerArrayLazy.Value(array); + private static readonly Lazy> CreateMarshalerArrayLazy = new(BindCreateMarshalerArray); private static Func BindCreateMarshalerArray() { var createMarshalerArray = HelperType.GetMethod("CreateMarshalerArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -463,7 +462,8 @@ private static Func BindCreateMarshalerArray() Expression.Convert(Expression.Call(createMarshalerArray, parms), typeof(object)), parms).Compile(); } - internal static readonly Func GetAbiArray; + internal static readonly Func GetAbiArray = (object box) => GetAbiArrayLazy.Value(box); + private static readonly Lazy> GetAbiArrayLazy = new(BindGetAbiArray); private static Func BindGetAbiArray() { var getAbiArray = HelperType.GetMethod("GetAbiArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -473,7 +473,8 @@ private static Func BindCreateMarshalerArray() Expression.Convert(Expression.Call(getAbiArray, parms), typeof((int, IntPtr))), parms).Compile(); } - internal static readonly Func FromAbiArray; + internal static readonly Func FromAbiArray = (object box) => FromAbiArrayLazy.Value(box); + private static readonly Lazy> FromAbiArrayLazy = new(BindFromAbiArray); private static Func BindFromAbiArray() { var fromAbiArray = HelperType.GetMethod("FromAbiArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -483,7 +484,8 @@ private static Func BindFromAbiArray() Expression.Call(fromAbiArray, parms), parms).Compile(); } - internal static readonly Func FromManagedArray; + internal static readonly Func FromManagedArray = (T[] array) => FromManagedArrayLazy.Value(array); + private static readonly Lazy> FromManagedArrayLazy = new(BindFromManagedArray); private static Func BindFromManagedArray() { var fromManagedArray = HelperType.GetMethod("FromManagedArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -493,7 +495,8 @@ private static Func BindFromAbiArray() Expression.Convert(Expression.Call(fromManagedArray, parms), typeof((int, IntPtr))), parms).Compile(); } - internal static readonly Action DisposeMarshalerArray; + internal static readonly Action DisposeMarshalerArray = (object box) => DisposeMarshalerArrayLazy.Value(box); + private static readonly Lazy> DisposeMarshalerArrayLazy = new(BindDisposeMarshalerArray); private static Action BindDisposeMarshalerArray() { var disposeMarshalerArray = HelperType.GetMethod("DisposeMarshalerArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -503,7 +506,8 @@ private static Action BindDisposeMarshalerArray() Expression.Call(disposeMarshalerArray, Expression.Convert(parms[0], MarshalerArrayType)), parms).Compile(); } - internal static readonly Action DisposeAbiArray; + internal static readonly Action DisposeAbiArray = (object box) => DisposeAbiArrayLazy.Value(box); + private static readonly Lazy> DisposeAbiArrayLazy = new(BindDisposeAbiArray); private static Action BindDisposeAbiArray() { var disposeAbiArray = HelperType.GetMethod("DisposeAbiArray", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); @@ -519,7 +523,7 @@ private static unsafe void CopyManagedFallback(T value, IntPtr dest) (value is null) ? IntPtr.Zero : ((IObjectReference) CreateMarshaler(value)).GetRef(); } - internal static unsafe void CopyManagedArray(T[] array, IntPtr data) => MarshalInterfaceHelper.CopyManagedArray(array, data, CopyManaged ?? CopyManagedFallback); + internal static unsafe void CopyManagedArray(T[] array, IntPtr data) => MarshalInterfaceHelper.CopyManagedArray(array, data, CopyManagedLazy.Value ?? CopyManagedFallback); } #if EMBED @@ -596,6 +600,10 @@ public void Dispose() return null; } var abi = ((int length, IntPtr data))box; + if (abi.data == IntPtr.Zero) + { + return null; + } var array = new T[abi.length]; var data = (byte*)abi.data.ToPointer(); var abi_element_size = Marshal.SizeOf(AbiType); @@ -781,6 +789,10 @@ public static unsafe T[] FromAbiArray(object box, Func fromAbi) return null; } var abi = ((int length, IntPtr data))box; + if (abi.data == IntPtr.Zero) + { + return null; + } var array = new T[abi.length]; var data = (IntPtr*)abi.data.ToPointer(); for (int i = 0; i < abi.length; i++) @@ -896,8 +908,10 @@ public static void DisposeMarshaler(IObjectReference objRef) public static void DisposeAbi(IntPtr ptr) { if (ptr == IntPtr.Zero) return; - // TODO: this should be a direct v-table call when function pointers are a thing - ObjectReference.Attach(ref ptr).Dispose(); + unsafe + { + (**(IUnknownVftbl**)ptr).Release(ptr); + } } } @@ -1014,8 +1028,7 @@ private static Func BindToAbi() private static Func BindAs() { - var helperType = typeof(T).GetHelperType(); - var vftblType = helperType.FindVftblType(); + var vftblType = HelperType.FindVftblType(); if (vftblType is not null) { var parms = new[] { Expression.Parameter(typeof(IObjectReference), "arg") }; @@ -1027,7 +1040,7 @@ private static Func BindAs() } else { - Guid iid = GuidGenerator.GetIID(helperType); + Guid iid = GuidGenerator.GetIID(HelperType); return obj => obj.As(iid); } } @@ -1206,10 +1219,10 @@ static Marshaler() CopyManaged = MarshalGeneric.CopyManaged; DisposeMarshaler = MarshalGeneric.DisposeMarshaler; DisposeAbi = MarshalGeneric.DisposeAbi; - CreateMarshalerArray = (T[] array) => MarshalGeneric.CreateMarshalerArray(array); - GetAbiArray = (object box) => MarshalGeneric.GetAbiArray(box); - FromAbiArray = (object box) => MarshalGeneric.FromAbiArray(box); - FromManagedArray = (T[] array) => MarshalGeneric.FromManagedArray(array); + CreateMarshalerArray = MarshalGeneric.CreateMarshalerArray; + GetAbiArray = MarshalGeneric.GetAbiArray; + FromAbiArray = MarshalGeneric.FromAbiArray; + FromManagedArray = MarshalGeneric.FromManagedArray; CopyManagedArray = (T[] array, IntPtr data) => MarshalGeneric.CopyManagedArray(array, data); DisposeMarshalerArray = (object box) => MarshalInterface.DisposeMarshalerArray(box); DisposeAbiArray = (object box) => MarshalInterface.DisposeAbiArray(box); @@ -1324,13 +1337,13 @@ unsafe void CopyEnum(object value, IntPtr dest) CopyManaged = MarshalGeneric.CopyManaged; DisposeMarshaler = MarshalGeneric.DisposeMarshaler; DisposeAbi = MarshalGeneric.DisposeAbi; - CreateMarshalerArray = (T[] array) => MarshalGeneric.CreateMarshalerArray(array); - GetAbiArray = (object box) => MarshalGeneric.GetAbiArray(box); - FromAbiArray = (object box) => MarshalGeneric.FromAbiArray(box); - FromManagedArray = (T[] array) => MarshalGeneric.FromManagedArray(array); + CreateMarshalerArray = MarshalGeneric.CreateMarshalerArray; + GetAbiArray = MarshalGeneric.GetAbiArray; + FromAbiArray = MarshalGeneric.FromAbiArray; + FromManagedArray = MarshalGeneric.FromManagedArray; CopyManagedArray = (T[] array, IntPtr data) => MarshalGeneric.CopyManagedArray(array, data); - DisposeMarshalerArray = (object box) => MarshalGeneric.DisposeMarshalerArray(box); - DisposeAbiArray = (object box) => MarshalGeneric.DisposeAbiArray(box); + DisposeMarshalerArray = MarshalGeneric.DisposeMarshalerArray; + DisposeAbiArray = MarshalGeneric.DisposeAbiArray; } RefAbiType = AbiType.MakeByRefType(); } diff --git a/src/WinRT.Runtime/Projections.cs b/src/WinRT.Runtime/Projections.cs index af2402581..9b0c9d1f3 100644 --- a/src/WinRT.Runtime/Projections.cs +++ b/src/WinRT.Runtime/Projections.cs @@ -22,9 +22,9 @@ static class Projections private static readonly ReaderWriterLockSlim rwlock = new ReaderWriterLockSlim(); private static readonly Dictionary CustomTypeToHelperTypeMappings = new Dictionary(); private static readonly Dictionary CustomAbiTypeToTypeMappings = new Dictionary(); - private static readonly Dictionary CustomAbiTypeNameToTypeMappings = new Dictionary(); + private static readonly Dictionary CustomAbiTypeNameToTypeMappings = new Dictionary(StringComparer.Ordinal); private static readonly Dictionary CustomTypeToAbiTypeNameMappings = new Dictionary(); - private static readonly HashSet ProjectedRuntimeClassNames = new HashSet(); + private static readonly HashSet ProjectedRuntimeClassNames = new HashSet(StringComparer.Ordinal); private static readonly HashSet ProjectedCustomTypeRuntimeClasses = new HashSet(); static Projections() diff --git a/src/WinRT.Runtime/Projections/DataErrorsChangedEventArgs.cs b/src/WinRT.Runtime/Projections/DataErrorsChangedEventArgs.cs index 8fae089ae..502520fde 100644 --- a/src/WinRT.Runtime/Projections/DataErrorsChangedEventArgs.cs +++ b/src/WinRT.Runtime/Projections/DataErrorsChangedEventArgs.cs @@ -137,7 +137,7 @@ public static IntPtr FromManaged(global::System.ComponentModel.DataErrorsChanged } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } + public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } public static string GetGuidSignature() { diff --git a/src/WinRT.Runtime/Projections/EventHandler.cs b/src/WinRT.Runtime/Projections/EventHandler.cs index 1e979851b..d7a049906 100644 --- a/src/WinRT.Runtime/Projections/EventHandler.cs +++ b/src/WinRT.Runtime/Projections/EventHandler.cs @@ -71,8 +71,10 @@ public NativeDelegateWrapper(ObjectReference _nativeDelegate; bool IWinRTObject.HasUnwrappableNativeObject => true; - ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); - ConcurrentDictionary IWinRTObject.AdditionalTypeData { get; } = new(); + private Lazy> _lazyQueryInterfaceCache = new(); + ConcurrentDictionary IWinRTObject.QueryInterfaceCache => _lazyQueryInterfaceCache.Value; + private Lazy> _lazyAdditionalTypeData = new(); + ConcurrentDictionary IWinRTObject.AdditionalTypeData => _lazyAdditionalTypeData.Value; #endif public void Invoke(object sender, T args) @@ -183,8 +185,10 @@ public NativeDelegateWrapper(ObjectReference _nativeDelegate; bool IWinRTObject.HasUnwrappableNativeObject => true; - ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); - ConcurrentDictionary IWinRTObject.AdditionalTypeData { get; } = new(); + private Lazy> _lazyQueryInterfaceCache = new(); + ConcurrentDictionary IWinRTObject.QueryInterfaceCache => _lazyQueryInterfaceCache.Value; + private Lazy> _lazyAdditionalTypeData = new(); + ConcurrentDictionary IWinRTObject.AdditionalTypeData => _lazyAdditionalTypeData.Value; #endif public unsafe void Invoke(object sender, EventArgs args) diff --git a/src/WinRT.Runtime/Projections/IPropertyValue.net5.cs b/src/WinRT.Runtime/Projections/IPropertyValue.net5.cs index a462bc323..7d85ae988 100644 --- a/src/WinRT.Runtime/Projections/IPropertyValue.net5.cs +++ b/src/WinRT.Runtime/Projections/IPropertyValue.net5.cs @@ -1207,15 +1207,15 @@ private static unsafe int Do_Abi_get_Type_0(IntPtr thisPtr, global::Windows.Foun { value = global::Windows.Foundation.PropertyType.Guid; } - else if (managedType.FullName == "Windows.Foundation.Point") + else if (string.CompareOrdinal(managedType.FullName, "Windows.Foundation.Point") == 0) { value = global::Windows.Foundation.PropertyType.Point; } - else if (managedType.FullName == "Windows.Foundation.Rect") + else if (string.CompareOrdinal(managedType.FullName, "Windows.Foundation.Rect") == 0) { value = global::Windows.Foundation.PropertyType.Rect; } - else if (managedType.FullName == "Windows.Foundation.Size") + else if (string.CompareOrdinal(managedType.FullName, "Windows.Foundation.Size") == 0) { value = global::Windows.Foundation.PropertyType.Size; } diff --git a/src/WinRT.Runtime/Projections/IPropertyValue.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IPropertyValue.netstandard2.0.cs index 6f47ffae8..97cb7de4f 100644 --- a/src/WinRT.Runtime/Projections/IPropertyValue.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IPropertyValue.netstandard2.0.cs @@ -1131,15 +1131,15 @@ private static unsafe int Do_Abi_get_Type_0(IntPtr thisPtr, global::Windows.Foun { value = global::Windows.Foundation.PropertyType.Guid; } - else if (managedType.FullName == "Windows.Foundation.Point") + else if (string.CompareOrdinal(managedType.FullName, "Windows.Foundation.Point") == 0) { value = global::Windows.Foundation.PropertyType.Point; } - else if (managedType.FullName == "Windows.Foundation.Rect") + else if (string.CompareOrdinal(managedType.FullName, "Windows.Foundation.Rect") == 0) { value = global::Windows.Foundation.PropertyType.Rect; } - else if (managedType.FullName == "Windows.Foundation.Size") + else if (string.CompareOrdinal(managedType.FullName, "Windows.Foundation.Size") == 0) { value = global::Windows.Foundation.PropertyType.Size; } diff --git a/src/WinRT.Runtime/Projections/IReferenceArray.net5.cs b/src/WinRT.Runtime/Projections/IReferenceArray.net5.cs index ccddfd163..e8d212265 100644 --- a/src/WinRT.Runtime/Projections/IReferenceArray.net5.cs +++ b/src/WinRT.Runtime/Projections/IReferenceArray.net5.cs @@ -100,7 +100,7 @@ public static IntPtr FromManaged(object value) } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } + public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IReferenceArray)); diff --git a/src/WinRT.Runtime/Projections/IReferenceArray.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IReferenceArray.netstandard2.0.cs index 710e3f6f0..2f6012a45 100644 --- a/src/WinRT.Runtime/Projections/IReferenceArray.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IReferenceArray.netstandard2.0.cs @@ -100,7 +100,7 @@ public static IntPtr FromManaged(object value) } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } + public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IReferenceArray)); diff --git a/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs b/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs index 56f26a5f6..55af1b009 100644 --- a/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs +++ b/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs @@ -237,7 +237,7 @@ public static IntPtr FromManaged(global::System.Collections.Specialized.NotifyCo } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } + public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } public static string GetGuidSignature() { diff --git a/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs b/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs index 3afcde5f2..744fb7128 100644 --- a/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs +++ b/src/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs @@ -72,8 +72,10 @@ public NativeDelegateWrapper(ObjectReference _nativeDelegate; bool IWinRTObject.HasUnwrappableNativeObject => true; - ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); - ConcurrentDictionary IWinRTObject.AdditionalTypeData { get; } = new(); + private Lazy> _lazyQueryInterfaceCache = new(); + ConcurrentDictionary IWinRTObject.QueryInterfaceCache => _lazyQueryInterfaceCache.Value; + private Lazy> _lazyAdditionalTypeData = new(); + ConcurrentDictionary IWinRTObject.AdditionalTypeData => _lazyAdditionalTypeData.Value; #endif public unsafe void Invoke(object sender, global::System.Collections.Specialized.NotifyCollectionChangedEventArgs e) diff --git a/src/WinRT.Runtime/Projections/Nullable.cs b/src/WinRT.Runtime/Projections/Nullable.cs index bdd334a42..cd9548234 100644 --- a/src/WinRT.Runtime/Projections/Nullable.cs +++ b/src/WinRT.Runtime/Projections/Nullable.cs @@ -100,7 +100,7 @@ public static IntPtr FromManaged(object value) } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } + public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(Nullable)); diff --git a/src/WinRT.Runtime/Projections/PropertyChangedEventArgs.cs b/src/WinRT.Runtime/Projections/PropertyChangedEventArgs.cs index 3b14adf7d..406f6b3b8 100644 --- a/src/WinRT.Runtime/Projections/PropertyChangedEventArgs.cs +++ b/src/WinRT.Runtime/Projections/PropertyChangedEventArgs.cs @@ -138,7 +138,7 @@ public static IntPtr FromManaged(global::System.ComponentModel.PropertyChangedEv } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } + public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } public static string GetGuidSignature() { diff --git a/src/WinRT.Runtime/Projections/PropertyChangedEventHandler.cs b/src/WinRT.Runtime/Projections/PropertyChangedEventHandler.cs index c06a8efd3..492a2631f 100644 --- a/src/WinRT.Runtime/Projections/PropertyChangedEventHandler.cs +++ b/src/WinRT.Runtime/Projections/PropertyChangedEventHandler.cs @@ -71,8 +71,10 @@ public NativeDelegateWrapper(ObjectReference _nativeDelegate; bool IWinRTObject.HasUnwrappableNativeObject => true; - ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); - ConcurrentDictionary IWinRTObject.AdditionalTypeData { get; } = new(); + private Lazy> _lazyQueryInterfaceCache = new(); + ConcurrentDictionary IWinRTObject.QueryInterfaceCache => _lazyQueryInterfaceCache.Value; + private Lazy> _lazyAdditionalTypeData = new(); + ConcurrentDictionary IWinRTObject.AdditionalTypeData => _lazyAdditionalTypeData.Value; #endif public unsafe void Invoke(object sender, global::System.ComponentModel.PropertyChangedEventArgs e) diff --git a/src/WinRT.Runtime/Projections/Uri.cs b/src/WinRT.Runtime/Projections/Uri.cs index 6234774e3..9032adaa6 100644 --- a/src/WinRT.Runtime/Projections/Uri.cs +++ b/src/WinRT.Runtime/Projections/Uri.cs @@ -146,7 +146,7 @@ public static IntPtr FromManaged(global::System.Uri value) } public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } + public static void DisposeAbi(IntPtr abi) { MarshalInspectable.DisposeAbi(abi); } public static string GetGuidSignature() { diff --git a/src/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs b/src/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs index 3c8c9ae05..e3a51e3fa 100644 --- a/src/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs +++ b/src/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs @@ -33,8 +33,10 @@ public SingleInterfaceOptimizedObject(Type type, IObjectReference objRef) IObjectReference IWinRTObject.NativeObject => _obj; bool IWinRTObject.HasUnwrappableNativeObject => false; - ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); - ConcurrentDictionary IWinRTObject.AdditionalTypeData { get; } = new(); + private Lazy> _lazyQueryInterfaceCache = new(); + ConcurrentDictionary IWinRTObject.QueryInterfaceCache => _lazyQueryInterfaceCache.Value; + private Lazy> _lazyAdditionalTypeData = new(); + ConcurrentDictionary IWinRTObject.AdditionalTypeData => _lazyAdditionalTypeData.Value; bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented) { diff --git a/src/WinRT.Runtime/TypeExtensions.cs b/src/WinRT.Runtime/TypeExtensions.cs index 4855fa030..b0dafca91 100644 --- a/src/WinRT.Runtime/TypeExtensions.cs +++ b/src/WinRT.Runtime/TypeExtensions.cs @@ -29,7 +29,7 @@ public static Type FindHelperType(this Type type) string fullTypeName = type.FullName; string ccwTypePrefix = "ABI.Impl."; - if (fullTypeName.StartsWith(ccwTypePrefix)) + if (fullTypeName.StartsWith(ccwTypePrefix, StringComparison.Ordinal)) { fullTypeName = fullTypeName.Substring(ccwTypePrefix.Length); } diff --git a/src/WinRT.Runtime/TypeNameSupport.cs b/src/WinRT.Runtime/TypeNameSupport.cs index 282a88e87..958fca8c0 100644 --- a/src/WinRT.Runtime/TypeNameSupport.cs +++ b/src/WinRT.Runtime/TypeNameSupport.cs @@ -32,7 +32,7 @@ enum TypeNameGenerationFlags static class TypeNameSupport { private static List projectionAssemblies = new List(); - private static ConcurrentDictionary typeNameCache = new ConcurrentDictionary() { ["TrackerCollection"] = null }; + private static ConcurrentDictionary typeNameCache = new ConcurrentDictionary(StringComparer.Ordinal) { ["TrackerCollection"] = null }; public static void RegisterProjectionAssembly(Assembly assembly) { @@ -69,7 +69,7 @@ public static (Type type, int remaining) FindTypeByName(ReadOnlySpan runti { // Assume that anonymous types are expando objects, whether declared 'dynamic' or not. // It may be necessary to detect otherwise and return System.Object. - if(runtimeClassName.StartsWith("<>f__AnonymousType".AsSpan())) + if(runtimeClassName.StartsWith("<>f__AnonymousType".AsSpan(), StringComparison.Ordinal)) { return (typeof(System.Dynamic.ExpandoObject), 0); } @@ -169,7 +169,7 @@ public static Type ResolvePrimitiveType(string primitiveTypeName) /// Returns a tuple containing the simple type name of the type, and generic type parameters if they exist, and the index of the end of the type name in the span. private static (string genericTypeName, Type[] genericTypes, int remaining) ParseGenericTypeName(ReadOnlySpan partialTypeName) { - int possibleEndOfSimpleTypeName = partialTypeName.IndexOfAny(new[] { ',', '>' }); + int possibleEndOfSimpleTypeName = partialTypeName.IndexOfAny(',', '>'); int endOfSimpleTypeName = partialTypeName.Length; if (possibleEndOfSimpleTypeName != -1) { From bf8659b671cca7bad8b1337cd2d776d1e8a7b191 Mon Sep 17 00:00:00 2001 From: Joshua Larkin <70237359+j0shuams@users.noreply.github.com> Date: Mon, 4 Oct 2021 11:26:07 -0700 Subject: [PATCH 03/11] cswinrt --- src/cswinrt/code_writers.h | 57 ++- src/cswinrt/main.cpp | 3 + src/cswinrt/settings.h | 1 + src/cswinrt/strings/ComInteropHelpers.cs | 131 +++++-- src/cswinrt/strings/WinRT.cs | 358 +++++++++--------- .../Microsoft.UI.Xaml.Controls.Primitives.cs | 14 +- .../Microsoft.UI.Xaml.Media.Animation.cs | 42 +- .../Microsoft.UI.Xaml.Media.Media3D.cs | 14 +- .../Microsoft.UI.Xaml.Media.cs | 14 +- .../Microsoft.UI.Xaml/Microsoft.UI.Xaml.cs | 84 +++- .../additions/Windows.Foundation/AsyncInfo.cs | 11 +- .../TaskToAsyncActionAdapter.cs | 2 +- .../TaskToAsyncActionWithProgressAdapter.cs | 2 +- .../TaskToAsyncInfoAdapter.cs | 2 +- .../TaskToAsyncOperationAdapter.cs | 2 +- ...TaskToAsyncOperationWithProgressAdapter.cs | 2 +- .../Windows.Foundation.SR.cs | 3 + .../Windows.Foundation/Windows.Foundation.cs | 7 +- .../IBufferByteAccess.cs | 2 +- .../Windows.Storage.Streams/IMarshal.cs | 16 +- .../NetFxToWinRtStreamAdapter.cs | 6 +- .../StreamOperationsImplementation.cs | 2 +- .../WinRtToNetFxStreamAdapter.cs | 14 +- .../WindowsRuntimeBuffer.cs | 7 +- .../WindowsRuntimeBufferExtensions.cs | 43 ++- .../WindowsRuntimeStreamExtensions.cs | 9 +- .../IStorageFolderHandleAccess.cs | 2 +- .../IStorageItemHandleAccess.cs | 2 +- .../WindowsRuntimeStorageExtensions.cs | 11 +- .../additions/Windows.UI/Windows.UI.cs | 14 +- 30 files changed, 571 insertions(+), 306 deletions(-) diff --git a/src/cswinrt/code_writers.h b/src/cswinrt/code_writers.h index 3a19cc72e..22fdaa3c5 100644 --- a/src/cswinrt/code_writers.h +++ b/src/cswinrt/code_writers.h @@ -64,6 +64,11 @@ namespace cswinrt return w.write_temp("%_%", method.Name(), get_vmethod_index(type, method)); } + std::string internal_if_embedded() + { + return (settings.embedded) ? "internal" : "public"; + } + bool is_type_blittable(type_semantics const& semantics, bool for_array = false) { return call(semantics, @@ -2521,12 +2526,13 @@ db_path.stem().string()); }; void write_static_class(writer& w, TypeDef const& type) - { - w.write(R"(%%public static class % + { // maybe + w.write(R"(%%% static class % { %})", bind(type), bind(type, true), + internal_if_embedded(), bind(type, typedef_name_type::Projected, false), bind(type) ); @@ -4890,12 +4896,13 @@ IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, { auto type_name = write_type_name_temp(w, type); - w.write(R"(%%public sealed class %: Attribute + w.write(R"(%%% sealed class %: Attribute { %} )", bind(type), bind(type, true), + internal_if_embedded(), type_name, [&](writer& w) { @@ -4932,7 +4939,7 @@ IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, bind(type), bind(type), bind(type, false), - is_exclusive_to(type) || is_projection_internal(type) ? "internal" : "public", + is_exclusive_to(type) || (is_projection_internal(type) || settings.embedded) ? "internal" : "public", // type_name, bind(type, object_type{}, false, false), bind(type) @@ -4952,7 +4959,7 @@ IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, w.write(R"([global::WinRT.ObjectReferenceWrapper(nameof(_obj))] % -public unsafe class % : % +% unsafe class % : % { % internal static ObjectReference FromAbi(IntPtr thisPtr)% @@ -4971,6 +4978,7 @@ _obj = obj;% )", // Interface abi implementation bind(type), + internal_if_embedded(), type_name, bind(type, typedef_name_type::CCW, false), // Vftbl @@ -5039,10 +5047,11 @@ public static Guid PIID = Vftbl.PIID; if (!nongeneric_delegates.empty()) { w.write(R"([global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] -public static class % +% static class % { %} )", + internal_if_embedded(), nongenerics_class, bind_each(nongeneric_delegates)); } @@ -5128,10 +5137,11 @@ AbiToProjectionVftablePtr = ComWrappersSupport.AllocateVtableMemory(typeof(@), s if (!nongeneric_delegates.empty()) { w.write(R"([global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] -public static class % +% static class % { %} )", +internal_if_embedded(), nongenerics_class, bind_each(nongeneric_delegates)); } @@ -5290,7 +5300,7 @@ private readonly % _comp; } w.write(R"(%[global::WinRT.ProjectedRuntimeClass(nameof(_default))] -%public %class %%, IEquatable<%> +%% %class %%, IEquatable<%> { public %IntPtr ThisPtr => _default.ThisPtr; @@ -5328,6 +5338,7 @@ private % AsInternal(InterfaceTag<%> _) => _default; )", bind(type), bind(type, false), + internal_if_embedded(), bind(type), type_name, bind(type, base_semantics, true, false), @@ -5435,7 +5446,7 @@ _defaultLazy = new Lazy<%>(() => GetDefaultReference<%.Vftbl>()); w.write(R"(% [global::WinRT.ProjectedRuntimeClass(nameof(_default))] [global::WinRT.ObjectReferenceWrapper(nameof(_inner))] -%public %class %%, IWinRTObject, IEquatable<%> +%% %class %%, IWinRTObject, IEquatable<%> { private IntPtr ThisPtr => _inner == null ? (((IWinRTObject)this).NativeObject).ThisPtr : _inner.ThisPtr; @@ -5473,6 +5484,7 @@ private % AsInternal(InterfaceTag<%> _) => _default; )", bind(type), bind(type, true), + internal_if_embedded(), bind(type), type_name, bind(type, base_semantics, true, false), @@ -5556,7 +5568,7 @@ global::System.Collections.Concurrent.ConcurrentDictionary value is null ? IntPtr.Zero : MarshalInterfaceHelper.GetAbi(value); @@ -5572,6 +5584,7 @@ public static void DisposeAbi(IntPtr abi) => MarshalInspectable.DisposeA public static unsafe void DisposeAbiArray(object box) => MarshalInspectable.DisposeAbiArray(box); } )", + internal_if_embedded(), abi_type_name, bind([&](writer& w) { @@ -5632,10 +5645,11 @@ public static unsafe void DisposeAbiArray(object box) => MarshalInspectable(type), bind(type, false), + internal_if_embedded(), bind(signature), bind(type, typedef_name_type::Projected, false), bind_list(", ", signature.params())); @@ -5654,7 +5668,7 @@ public static unsafe void DisposeAbiArray(object box) => MarshalInspectable _nativeDelegate; bool IWinRTObject.HasUnwrappableNativeObject => true; private Lazy> _lazyQueryInterfaceCache = new(); @@ -5727,6 +5741,7 @@ private static unsafe int Do_Abi_Invoke% )", bind(type), + internal_if_embedded(), type.TypeName(), type_params, [&](writer& w) { @@ -5936,11 +5951,12 @@ public static Guid PIID = GuidGenerator.CreateIID(typeof(%));)", auto enum_underlying_type = is_flags_enum(type) ? "uint" : "int"; - w.write(R"(%%public enum % : % + w.write(R"(%%% enum % : % { )", bind(type), bind(type, true), + internal_if_embedded(), bind(type, typedef_name_type::Projected, false), enum_underlying_type); { for (auto&& field : type.FieldList()) @@ -5990,7 +6006,7 @@ public static Guid PIID = GuidGenerator.CreateIID(typeof(%));)", fields.emplace_back(field_info); } - w.write(R"(%%public struct %: IEquatable<%> + w.write(R"(%%% struct %: IEquatable<%> { % public %(%) @@ -6008,6 +6024,7 @@ public override int GetHashCode() => %; // struct bind(type), bind(type, true), + internal_if_embedded(), name, name, bind_each([](writer& w, auto&& field) @@ -6052,7 +6069,10 @@ public override int GetHashCode() => %; return; } - w.write("[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\npublic struct %\n{\n", bind(type, typedef_name_type::ABI, false)); + w.write("[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]\n% struct %\n{\n", + internal_if_embedded(), + bind(type, typedef_name_type::ABI, false)); + for (auto&& field : type.FieldList()) { w.write("public "); @@ -6404,7 +6424,7 @@ bind(type) using System; namespace WinRT { -public static class Module +% static class Module { public static unsafe IntPtr GetActivationFactory(String runtimeClassId) {% @@ -6413,6 +6433,7 @@ return IntPtr.Zero; } } )", + internal_if_embedded(), bind_each([](writer& w, TypeDef const& type) { w.write(R"( diff --git a/src/cswinrt/main.cpp b/src/cswinrt/main.cpp index 5cee2f320..51477f172 100644 --- a/src/cswinrt/main.cpp +++ b/src/cswinrt/main.cpp @@ -35,6 +35,7 @@ namespace cswinrt { "target", 0, 1, "", "Target TFM for projection. Omit for compatibility with newest TFM (net5.0)." }, { "component", 0, 0, {}, "Generate component projection." }, { "verbose", 0, 0, {}, "Show detailed progress information" }, + { "embedded", 0, 0, {}, "Generate the projection as internal."}, { "help", 0, option::no_max, {}, "Show detailed help" }, { "?", 0, option::no_max, {}, {} }, }; @@ -84,6 +85,7 @@ Where is one or more of: throw usage_exception{}; } + settings.verbose = args.exists("verbose"); auto target = args.value("target"); if (!target.empty() && target != "netstandard2.0" && !starts_with(target, "net5.0") && !starts_with(target, "net6.0")) @@ -92,6 +94,7 @@ Where is one or more of: } settings.netstandard_compat = target == "netstandard2.0"; settings.component = args.exists("component"); + settings.embedded = args.exists("embedded"); settings.input = args.files("input", database::is_database); for (auto && include : args.values("include")) diff --git a/src/cswinrt/settings.h b/src/cswinrt/settings.h index f943e98bb..5b497a37d 100644 --- a/src/cswinrt/settings.h +++ b/src/cswinrt/settings.h @@ -12,6 +12,7 @@ namespace cswinrt winmd::reader::filter filter; bool netstandard_compat{}; bool component{}; + bool embedded{}; }; extern settings_type settings; diff --git a/src/cswinrt/strings/ComInteropHelpers.cs b/src/cswinrt/strings/ComInteropHelpers.cs index 1e9319c22..9ddf2e75e 100644 --- a/src/cswinrt/strings/ComInteropHelpers.cs +++ b/src/cswinrt/strings/ComInteropHelpers.cs @@ -55,7 +55,12 @@ internal interface IWindowNative IntPtr WindowHandle { get; } } - public static class WindowNative +#if EMBED + internal +#else + public +#endif + static class WindowNative { public static IntPtr GetWindowHandle(object target) => target.As().WindowHandle; } @@ -68,7 +73,12 @@ internal interface IInitializeWithWindow void Initialize(IntPtr hwnd); } - public static class InitializeWithWindow +#if EMBED + internal +#else + public +#endif + static class InitializeWithWindow { public static void Initialize(object target, IntPtr hwnd) => target.As().Initialize(hwnd); } @@ -77,10 +87,15 @@ public static class InitializeWithWindow namespace Windows.ApplicationModel.DataTransfer.DragDrop.Core { #if UAC_VERSION_1 -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.10240.0")] #endif - public static class DragDropManagerInterop +#if EMBED + internal +#else + public +#endif + static class DragDropManagerInterop { private static IDragDropManagerInterop dragDropManagerInterop = CoreDragDropManager.As(); @@ -96,10 +111,15 @@ public static CoreDragDropManager GetForWindow(IntPtr appWindow) namespace Windows.Graphics.Printing { #if UAC_VERSION_1 -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.10240.0")] #endif - public static class PrintManagerInterop +#if EMBED + internal +#else + public +#endif + static class PrintManagerInterop { private static IPrintManagerInterop printManagerInterop = PrintManager.As(); @@ -121,10 +141,15 @@ public static IAsyncOperation ShowPrintUIForWindowAsync(IntPtr appWindow) namespace Windows.Media { #if UAC_VERSION_1 -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.10240.0")] #endif - public static class SystemMediaTransportControlsInterop +#if EMBED + internal +#else + public +#endif + static class SystemMediaTransportControlsInterop { private static ISystemMediaTransportControlsInterop systemMediaTransportControlsInterop = SystemMediaTransportControls.As(); @@ -140,10 +165,15 @@ public static SystemMediaTransportControls GetForWindow(IntPtr appWindow) namespace Windows.Media.PlayTo { #if UAC_VERSION_1 -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.10240.0")] #endif - public static class PlayToManagerInterop +#if EMBED + internal +#else + public +#endif + static class PlayToManagerInterop { private static IPlayToManagerInterop playToManagerInterop = PlayToManager.As(); @@ -164,10 +194,15 @@ public static void ShowPlayToUIForWindow(IntPtr appWindow) namespace Windows.Security.Credentials.UI { #if UAC_VERSION_1 -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.10240.0")] #endif - public static class UserConsentVerifierInterop +#if EMBED + internal +#else + public +#endif + static class UserConsentVerifierInterop { private static IUserConsentVerifierInterop userConsentVerifierInterop = UserConsentVerifier.As(); @@ -183,10 +218,15 @@ public static IAsyncOperation RequestVerification namespace Windows.Security.Authentication.Web.Core { #if UAC_VERSION_1 -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.10240.0")] #endif - public static class WebAuthenticationCoreManagerInterop +#if EMBED + internal +#else + public +#endif + static class WebAuthenticationCoreManagerInterop { private static IWebAuthenticationCoreManagerInterop webAuthenticationCoreManagerInterop = WebAuthenticationCoreManager.As(); @@ -208,10 +248,15 @@ public static IAsyncOperation RequestTokenWithWebAccountF namespace Windows.UI.ApplicationSettings { #if UAC_VERSION_1 -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.10240.0")] #endif - public static class AccountsSettingsPaneInterop +#if EMBED + internal +#else + public +#endif + static class AccountsSettingsPaneInterop { private static IAccountsSettingsPaneInterop accountsSettingsPaneInterop = AccountsSettingsPane.As(); @@ -239,10 +284,15 @@ public static IAsyncAction ShowAddAccountForWindowAsync(IntPtr appWindow) namespace Windows.UI.Input { #if UAC_VERSION_3 -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.14393.0")] #endif - public static class RadialControllerConfigurationInterop +#if EMBED + internal +#else + public +#endif + static class RadialControllerConfigurationInterop { private static IRadialControllerConfigurationInterop radialControllerConfigurationInterop = RadialControllerConfiguration.As(); @@ -254,10 +304,15 @@ public static RadialControllerConfiguration GetForWindow(IntPtr hwnd) } } -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.14393.0")] #endif - public static class RadialControllerInterop +#if EMBED + internal +#else + public +#endif + static class RadialControllerInterop { private static IRadialControllerInterop radialControllerInterop = RadialController.As(); @@ -273,10 +328,15 @@ public static RadialController CreateForWindow(IntPtr hwnd) namespace Windows.UI.Input.Core { #if UAC_VERSION_4 -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.15063.0")] #endif - public static class RadialControllerIndependentInputSourceInterop +#if EMBED + internal +#else + public +#endif + static class RadialControllerIndependentInputSourceInterop { private static IRadialControllerIndependentInputSourceInterop radialControllerIndependentInputSourceInterop = RadialControllerIndependentInputSource.As(); @@ -293,10 +353,15 @@ public static RadialControllerIndependentInputSource CreateForWindow(IntPtr hwnd namespace Windows.UI.Input.Spatial { #if UAC_VERSION_2 -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.10586.0")] #endif - public static class SpatialInteractionManagerInterop +#if EMBED + internal +#else + public +#endif + static class SpatialInteractionManagerInterop { private static ISpatialInteractionManagerInterop spatialInteractionManagerInterop = SpatialInteractionManager.As(); @@ -312,10 +377,15 @@ public static SpatialInteractionManager GetForWindow(IntPtr window) namespace Windows.UI.ViewManagement { #if UAC_VERSION_1 -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.10240.0")] #endif - public static class InputPaneInterop +#if EMBED + internal +#else + public +#endif + static class InputPaneInterop { private static IInputPaneInterop inputPaneInterop = InputPane.As(); @@ -326,10 +396,15 @@ public static InputPane GetForWindow(IntPtr appWindow) } } -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("Windows10.0.10240.0")] #endif - public static class UIViewSettingsInterop +#if EMBED + internal +#else + public +#endif + static class UIViewSettingsInterop { private static IUIViewSettingsInterop uIViewSettingsInterop = UIViewSettings.As(); diff --git a/src/cswinrt/strings/WinRT.cs b/src/cswinrt/strings/WinRT.cs index b1cdf2354..32e577ecc 100644 --- a/src/cswinrt/strings/WinRT.cs +++ b/src/cswinrt/strings/WinRT.cs @@ -4,9 +4,9 @@ using System.Reflection; using System.Runtime.InteropServices; using System.Threading; -using System.Linq.Expressions; -using System.Diagnostics; -using WinRT.Interop; +using System.Linq.Expressions; +using System.Diagnostics; +using WinRT.Interop; using System.Runtime.CompilerServices; #pragma warning disable 0169 // The field 'xxx' is never used @@ -117,9 +117,9 @@ public static bool TryLoad(string fileName, out DllModule module) { if (_cache.TryGetValue(fileName, out module)) { - return true; + return true; } - else if (TryCreate(fileName, out module)) + else if (TryCreate(fileName, out module)) { _cache[fileName] = module; return true; @@ -128,8 +128,8 @@ public static bool TryLoad(string fileName, out DllModule module) } } - static bool TryCreate(string fileName, out DllModule module) - { + static bool TryCreate(string fileName, out DllModule module) + { // Explicitly look for module in the same directory as this one, and // use altered search path to ensure any dependencies in the same directory are found. var moduleHandle = Platform.LoadLibraryExW(System.IO.Path.Combine(_currentModuleDirectory, fileName), IntPtr.Zero, /* LOAD_WITH_ALTERED_SEARCH_PATH */ 8); @@ -142,21 +142,21 @@ static bool TryCreate(string fileName, out DllModule module) if (moduleHandle == IntPtr.Zero) { module = null; - return false; + return false; } - var getActivationFactory = Platform.GetProcAddress(moduleHandle, nameof(DllGetActivationFactory)); + var getActivationFactory = Platform.GetProcAddress(moduleHandle, nameof(DllGetActivationFactory)); if (getActivationFactory == IntPtr.Zero) { module = null; - return false; - } + return false; + } module = new DllModule( fileName, moduleHandle, Marshal.GetDelegateForFunctionPointer(getActivationFactory)); - return true; + return true; } DllModule(string fileName, IntPtr moduleHandle, DllGetActivationFactory getActivationFactory) @@ -176,14 +176,14 @@ public unsafe (ObjectReference obj, int hr) GetActivati { IntPtr instancePtr; var hstrRuntimeClassId = MarshalString.CreateMarshaler(runtimeClassId); - try - { - int hr = _GetActivationFactory(MarshalString.GetAbi(hstrRuntimeClassId), out instancePtr); - return (hr == 0 ? ObjectReference.Attach(ref instancePtr) : null, hr); + try + { + int hr = _GetActivationFactory(MarshalString.GetAbi(hstrRuntimeClassId), out instancePtr); + return (hr == 0 ? ObjectReference.Attach(ref instancePtr) : null, hr); } finally - { - hstrRuntimeClassId.Dispose(); + { + hstrRuntimeClassId.Dispose(); } } @@ -286,10 +286,10 @@ public BaseActivationFactory(string typeNamespace, string typeFullName) while (true) { DllModule module = null; - if (DllModule.TryLoad(moduleName + ".dll", out module)) - { + if (DllModule.TryLoad(moduleName + ".dll", out module)) + { (_IActivationFactory, _) = module.GetActivationFactory(typeFullName); - if (_IActivationFactory != null) { return; } + if (_IActivationFactory != null) { return; } } var lastSegment = moduleName.LastIndexOf(".", StringComparison.Ordinal); @@ -364,114 +364,114 @@ protected abstract class State : IDisposable { public EventRegistrationToken token; public TDelegate del; - public System.Delegate eventInvoke; - private bool disposedValue; + public System.Delegate eventInvoke; + private bool disposedValue; private readonly IntPtr obj; - private readonly int index; - private readonly System.WeakReference cacheEntry; + private readonly int index; + private readonly System.WeakReference cacheEntry; private IntPtr eventInvokePtr; private IntPtr referenceTrackerTargetPtr; - - protected State(IntPtr obj, int index) - { - this.obj = obj; - this.index = index; - eventInvoke = GetEventInvoke(); - cacheEntry = new System.WeakReference(this); - } - - // The lifetime of this object is managed by the delegate / eventInvoke - // through its target reference to it. Once the delegate no longer has - // any references, this object will also no longer have any references. - ~State() - { - Dispose(false); - } - - // Allows to retrieve a singleton like weak reference to use - // with the cache to allow for proper removal with comparision. - public System.WeakReference GetWeakReferenceForCache() - { - return cacheEntry; - } - - protected abstract System.Delegate GetEventInvoke(); - - protected virtual void Dispose(bool disposing) - { - // Uses the dispose pattern to ensure we only remove - // from the cache once: either via unsubscribe or via - // the finalizer. - if (!disposedValue) - { - Cache.Remove(obj, index, cacheEntry); - disposedValue = true; - } - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - public void InitalizeReferenceTracking(IntPtr ptr) - { - eventInvokePtr = ptr; - Guid iid = typeof(IReferenceTrackerTargetVftbl).GUID; - int hr = Marshal.QueryInterface(ptr, ref iid, out referenceTrackerTargetPtr); - if (hr != 0) - { - referenceTrackerTargetPtr = default; - } - else - { - // We don't want to keep ourselves alive and as long as this object - // is alive, the CCW still exists. - Marshal.Release(referenceTrackerTargetPtr); - } - } - - public bool HasComReferences() - { - if (eventInvokePtr != default) - { - IUnknownVftbl vftblIUnknown = **(IUnknownVftbl**)eventInvokePtr; - vftblIUnknown.AddRef(eventInvokePtr); - uint comRefCount = vftblIUnknown.Release(eventInvokePtr); - if (comRefCount != 0) - { - return true; - } - } - - if (referenceTrackerTargetPtr != default) - { - IReferenceTrackerTargetVftbl vftblReferenceTracker = **(IReferenceTrackerTargetVftbl**)referenceTrackerTargetPtr; - vftblReferenceTracker.AddRefFromReferenceTracker(referenceTrackerTargetPtr); - uint refTrackerCount = vftblReferenceTracker.ReleaseFromReferenceTracker(referenceTrackerTargetPtr); - if (refTrackerCount != 0) - { - // Note we can't tell if the reference tracker ref is pegged or not, so this is best effort where if there - // are any reference tracker references, we assume the event has references. - return true; - } - } - - return false; - } + + protected State(IntPtr obj, int index) + { + this.obj = obj; + this.index = index; + eventInvoke = GetEventInvoke(); + cacheEntry = new System.WeakReference(this); + } + + // The lifetime of this object is managed by the delegate / eventInvoke + // through its target reference to it. Once the delegate no longer has + // any references, this object will also no longer have any references. + ~State() + { + Dispose(false); + } + + // Allows to retrieve a singleton like weak reference to use + // with the cache to allow for proper removal with comparision. + public System.WeakReference GetWeakReferenceForCache() + { + return cacheEntry; + } + + protected abstract System.Delegate GetEventInvoke(); + + protected virtual void Dispose(bool disposing) + { + // Uses the dispose pattern to ensure we only remove + // from the cache once: either via unsubscribe or via + // the finalizer. + if (!disposedValue) + { + Cache.Remove(obj, index, cacheEntry); + disposedValue = true; + } + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + public void InitalizeReferenceTracking(IntPtr ptr) + { + eventInvokePtr = ptr; + Guid iid = typeof(IReferenceTrackerTargetVftbl).GUID; + int hr = Marshal.QueryInterface(ptr, ref iid, out referenceTrackerTargetPtr); + if (hr != 0) + { + referenceTrackerTargetPtr = default; + } + else + { + // We don't want to keep ourselves alive and as long as this object + // is alive, the CCW still exists. + Marshal.Release(referenceTrackerTargetPtr); + } + } + + public bool HasComReferences() + { + if (eventInvokePtr != default) + { + IUnknownVftbl vftblIUnknown = **(IUnknownVftbl**)eventInvokePtr; + vftblIUnknown.AddRef(eventInvokePtr); + uint comRefCount = vftblIUnknown.Release(eventInvokePtr); + if (comRefCount != 0) + { + return true; + } + } + + if (referenceTrackerTargetPtr != default) + { + IReferenceTrackerTargetVftbl vftblReferenceTracker = **(IReferenceTrackerTargetVftbl**)referenceTrackerTargetPtr; + vftblReferenceTracker.AddRefFromReferenceTracker(referenceTrackerTargetPtr); + uint refTrackerCount = vftblReferenceTracker.ReleaseFromReferenceTracker(referenceTrackerTargetPtr); + if (refTrackerCount != 0) + { + // Note we can't tell if the reference tracker ref is pegged or not, so this is best effort where if there + // are any reference tracker references, we assume the event has references. + return true; + } + } + + return false; + } } - protected System.WeakReference _state; - - protected EventSource(IObjectReference obj, - delegate* unmanaged[Stdcall] addHandler, - delegate* unmanaged[Stdcall] removeHandler, + protected System.WeakReference _state; + + protected EventSource(IObjectReference obj, + delegate* unmanaged[Stdcall] addHandler, + delegate* unmanaged[Stdcall] removeHandler, int index = 0) { - _obj = obj; + _obj = obj; _addHandler = addHandler; - _removeHandler = removeHandler; - _index = index; + _removeHandler = removeHandler; + _index = index; _state = Cache.GetState(obj, index); } @@ -479,8 +479,8 @@ protected EventSource(IObjectReference obj, protected abstract IntPtr GetAbi(IObjectReference marshaler); - protected abstract void DisposeMarshaler(IObjectReference marshaler); - + protected abstract void DisposeMarshaler(IObjectReference marshaler); + protected abstract State CreateEventState(); public void Subscribe(TDelegate del) @@ -490,8 +490,8 @@ public void Subscribe(TDelegate del) State state = null; bool registerHandler = _state is null || - !_state.TryGetTarget(out state) || - // We have a wrapper delegate, but no longer has any references from any event source. + !_state.TryGetTarget(out state) || + // We have a wrapper delegate, but no longer has any references from any event source. !state.HasComReferences(); if (registerHandler) { @@ -507,7 +507,7 @@ _state is null || var marshaler = CreateMarshaler(eventInvoke); try { - var nativeDelegate = GetAbi(marshaler); + var nativeDelegate = GetAbi(marshaler); state.InitalizeReferenceTracking(nativeDelegate); ExceptionHelpers.ThrowExceptionForHR(_addHandler(_obj.ThisPtr, nativeDelegate, out state.token)); } @@ -558,9 +558,9 @@ private class Cache private readonly ConcurrentDictionary> states = new ConcurrentDictionary>(); private static readonly ReaderWriterLockSlim cachesLock = new ReaderWriterLockSlim(); - private static readonly ConcurrentDictionary caches = new ConcurrentDictionary(); - - + private static readonly ConcurrentDictionary caches = new ConcurrentDictionary(); + + private Cache Update(IWeakReference target, int index, System.WeakReference state) { // If target no longer exists, destroy cache @@ -608,17 +608,17 @@ public static void Create(IObjectReference obj, int index, System.WeakReference< // do not implement IWeakReferenceSource, so static codegen caching approach is also used. IWeakReference target = null; try - { -#if NETSTANDARD2_0 - var weakRefSource = (IWeakReferenceSource)typeof(IWeakReferenceSource).GetHelperType().GetConstructor(new[] { typeof(IObjectReference) }).Invoke(new object[] { obj }); + { +#if !NET + var weakRefSource = (IWeakReferenceSource)typeof(IWeakReferenceSource).GetHelperType().GetConstructor(new[] { typeof(IObjectReference) }).Invoke(new object[] { obj }); #else var weakRefSource = ((object)new WinRT.IInspectable(obj)) as IWeakReferenceSource; #endif - if (weakRefSource == null) - { - return; + if (weakRefSource == null) + { + return; } - target = weakRefSource.GetWeakReference(); + target = weakRefSource.GetWeakReference(); } catch (Exception) { @@ -651,30 +651,30 @@ public static System.WeakReference GetState(IObjectReference obj, int ind public static void Remove(IntPtr thisPtr, int index, System.WeakReference state) { if (caches.TryGetValue(thisPtr, out var cache)) - { -#if NETSTANDARD2_0 - // https://devblogs.microsoft.com/pfxteam/little-known-gems-atomic-conditional-removals-from-concurrentdictionary/ - ((ICollection>>)cache.states).Remove( - new KeyValuePair>(index, state)); + { +#if !NET + // https://devblogs.microsoft.com/pfxteam/little-known-gems-atomic-conditional-removals-from-concurrentdictionary/ + ((ICollection>>)cache.states).Remove( + new KeyValuePair>(index, state)); #else cache.states.TryRemove(new KeyValuePair>(index, state)); #endif - // using double-checked lock idiom - if (cache.states.IsEmpty) - { - cachesLock.EnterWriteLock(); - try - { - if (cache.states.IsEmpty) - { - caches.TryRemove(thisPtr, out var _); - } - } - finally - { - cachesLock.ExitWriteLock(); - } - } + // using double-checked lock idiom + if (cache.states.IsEmpty) + { + cachesLock.EnterWriteLock(); + try + { + if (cache.states.IsEmpty) + { + caches.TryRemove(thisPtr, out var _); + } + } + finally + { + cachesLock.ExitWriteLock(); + } + } } } } @@ -698,26 +698,26 @@ protected override void DisposeMarshaler(IObjectReference marshaler) => protected override IntPtr GetAbi(IObjectReference marshaler) => marshaler is null ? IntPtr.Zero : ABI.System.EventHandler.GetAbi(marshaler); - protected override State CreateEventState() => - new EventState(_obj.ThisPtr, _index); - - private sealed class EventState : State - { - public EventState(IntPtr obj, int index) - : base(obj, index) - { - } - - protected override Delegate GetEventInvoke() - { - System.EventHandler handler = (System.Object obj, T e) => - { - var localDel = del; - if (localDel != null) - localDel.Invoke(obj, e); - }; - return handler; - } + protected override State CreateEventState() => + new EventState(_obj.ThisPtr, _index); + + private sealed class EventState : State + { + public EventState(IntPtr obj, int index) + : base(obj, index) + { + } + + protected override Delegate GetEventInvoke() + { + System.EventHandler handler = (System.Object obj, T e) => + { + var localDel = del; + if (localDel != null) + localDel.Invoke(obj, e); + }; + return handler; + } } } @@ -862,7 +862,9 @@ internal static class ProjectionInitializer #pragma warning restore 0436 internal static void InitalizeProjection() { +#if !EMBED ComWrappersSupport.RegisterProjectionAssembly(typeof(ProjectionInitializer).Assembly); +#endif } } } diff --git a/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Controls.Primitives/Microsoft.UI.Xaml.Controls.Primitives.cs b/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Controls.Primitives/Microsoft.UI.Xaml.Controls.Primitives.cs index ff5bdd70b..3a39fd93e 100644 --- a/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Controls.Primitives/Microsoft.UI.Xaml.Controls.Primitives.cs +++ b/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Controls.Primitives/Microsoft.UI.Xaml.Controls.Primitives.cs @@ -5,7 +5,12 @@ namespace Microsoft.UI.Xaml.Controls.Primitives [global::WinRT.WindowsRuntimeType("Microsoft.UI")] [StructLayout(LayoutKind.Sequential)] - public struct GeneratorPosition +#if EMBED + internal +#else + public +#endif + struct GeneratorPosition { private int _index; private int _offset; @@ -55,7 +60,12 @@ public override bool Equals(object o) namespace ABI.Microsoft.UI.Xaml.Controls.Primitives { - public static class GeneratorPosition +#if EMBED + internal +#else + public +#endif + static class GeneratorPosition { public static string GetGuidSignature() => $"struct(Microsoft.UI.Xaml.Controls.Primitives.GeneratorPosition;i4;i4)"; } diff --git a/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Media.Animation/Microsoft.UI.Xaml.Media.Animation.cs b/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Media.Animation/Microsoft.UI.Xaml.Media.Animation.cs index 8eaf77eef..8eeb51f6a 100644 --- a/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Media.Animation/Microsoft.UI.Xaml.Media.Animation.cs +++ b/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Media.Animation/Microsoft.UI.Xaml.Media.Animation.cs @@ -5,7 +5,12 @@ namespace Microsoft.UI.Xaml.Media.Animation [global::WinRT.WindowsRuntimeType("Microsoft.UI")] [StructLayout(LayoutKind.Sequential)] - public struct KeyTime +#if EMBED + internal +#else + public +#endif + struct KeyTime { private TimeSpan _timeSpan; @@ -73,7 +78,12 @@ public TimeSpan TimeSpan } [global::WinRT.WindowsRuntimeType("Microsoft.UI")] - public enum RepeatBehaviorType +#if EMBED + internal +#else + public +#endif + enum RepeatBehaviorType { Count, Duration, @@ -82,7 +92,12 @@ public enum RepeatBehaviorType [global::WinRT.WindowsRuntimeType("Microsoft.UI")] [StructLayout(LayoutKind.Sequential)] - public struct RepeatBehavior : IFormattable +#if EMBED + internal +#else + public +#endif + struct RepeatBehavior : IFormattable { private double _Count; private TimeSpan _Duration; @@ -269,7 +284,12 @@ public override int GetHashCode() namespace ABI.Microsoft.UI.Xaml.Media.Animation { - public static class KeyTime +#if EMBED + internal +#else + public +#endif + static class KeyTime { public static string GetGuidSignature() { @@ -278,7 +298,12 @@ public static string GetGuidSignature() } } - public static class RepeatBehavior +#if EMBED + internal +#else + public +#endif + static class RepeatBehavior { public static string GetGuidSignature() { @@ -287,7 +312,12 @@ public static string GetGuidSignature() } } - public static class RepeatBehaviorType +#if EMBED + internal +#else + public +#endif + static class RepeatBehaviorType { public static string GetGuidSignature() => "enum(Microsoft.UI.Xaml.Media.Animation.RepeatBehaviorType;i4)"; } diff --git a/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Media.Media3D/Microsoft.UI.Xaml.Media.Media3D.cs b/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Media.Media3D/Microsoft.UI.Xaml.Media.Media3D.cs index d1d32c78f..8d1ca129e 100644 --- a/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Media.Media3D/Microsoft.UI.Xaml.Media.Media3D.cs +++ b/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Media.Media3D/Microsoft.UI.Xaml.Media.Media3D.cs @@ -5,7 +5,12 @@ namespace Microsoft.UI.Xaml.Media.Media3D [global::WinRT.WindowsRuntimeType("Microsoft.UI")] [StructLayout(LayoutKind.Sequential)] - public struct Matrix3D : IFormattable +#if EMBED + internal +#else + public +#endif + struct Matrix3D : IFormattable { // Assuming this matrix has fourth column of 0,0,0,1 and isn't identity this function: // Returns false if HasInverse is false, otherwise inverts the matrix. @@ -692,7 +697,12 @@ private static bool IsZero(double value) namespace ABI.Microsoft.UI.Xaml.Media.Media3D { - public static class Matrix3D +#if EMBED + internal +#else + public +#endif + static class Matrix3D { public static string GetGuidSignature() => $"struct(Microsoft.UI.Xaml.Media.Media3D.Matrix3D;f8;f8;f8;f8;f8;f8;f8;f8;f8;f8;f8;f8;f8;f8;f8;f8)"; diff --git a/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Media/Microsoft.UI.Xaml.Media.cs b/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Media/Microsoft.UI.Xaml.Media.cs index da2c6ace3..14a7436b5 100644 --- a/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Media/Microsoft.UI.Xaml.Media.cs +++ b/src/cswinrt/strings/additions/Microsoft.UI.Xaml.Media/Microsoft.UI.Xaml.Media.cs @@ -5,7 +5,12 @@ namespace Microsoft.UI.Xaml.Media [global::WinRT.WindowsRuntimeType("Microsoft.UI")] [StructLayout(LayoutKind.Sequential)] - public struct Matrix : IFormattable +#if EMBED + internal +#else + public +#endif + struct Matrix : IFormattable { public Matrix(double m11, double m12, double m21, double m22, @@ -245,7 +250,12 @@ private static bool Equals(Matrix matrix1, Matrix matrix2) namespace ABI.Microsoft.UI.Xaml.Media { - public static class Matrix +#if EMBED + internal +#else + public +#endif + static class Matrix { public static string GetGuidSignature() => $"struct(Microsoft.UI.Xaml.Media.Matrix;f8;f8;f8;f8;f8;f8)"; } diff --git a/src/cswinrt/strings/additions/Microsoft.UI.Xaml/Microsoft.UI.Xaml.cs b/src/cswinrt/strings/additions/Microsoft.UI.Xaml/Microsoft.UI.Xaml.cs index f4b9fefeb..c96e1ff61 100644 --- a/src/cswinrt/strings/additions/Microsoft.UI.Xaml/Microsoft.UI.Xaml.cs +++ b/src/cswinrt/strings/additions/Microsoft.UI.Xaml/Microsoft.UI.Xaml.cs @@ -5,7 +5,12 @@ namespace Microsoft.UI.Xaml [global::WinRT.WindowsRuntimeType("Microsoft.UI")] [StructLayout(LayoutKind.Sequential)] - public struct CornerRadius +#if EMBED + internal +#else + public +#endif + struct CornerRadius { private double _TopLeft; private double _TopRight; @@ -146,7 +151,12 @@ public double BottomLeft } [global::WinRT.WindowsRuntimeType("Microsoft.UI")] - public enum GridUnitType +#if EMBED + internal +#else + public +#endif + enum GridUnitType { Auto = 0, Pixel, @@ -155,7 +165,12 @@ public enum GridUnitType [global::WinRT.WindowsRuntimeType("Microsoft.UI")] [StructLayout(LayoutKind.Sequential)] - public struct GridLength +#if EMBED + internal +#else + public +#endif + struct GridLength { private readonly double _unitValue; private readonly GridUnitType _unitType; @@ -267,7 +282,12 @@ internal string ToString(global::System.Globalization.CultureInfo cultureInfo) [global::WinRT.WindowsRuntimeType("Microsoft.UI")] [StructLayout(LayoutKind.Sequential)] - public struct Thickness +#if EMBED + internal +#else + public +#endif + struct Thickness { private double _Left; private double _Top; @@ -374,7 +394,12 @@ public override int GetHashCode() } [global::WinRT.WindowsRuntimeType("Microsoft.UI")] - public enum DurationType +#if EMBED + internal +#else + public +#endif + enum DurationType { Automatic, TimeSpan, @@ -383,7 +408,12 @@ public enum DurationType [global::WinRT.WindowsRuntimeType("Microsoft.UI")] [StructLayout(LayoutKind.Sequential)] - public struct Duration +#if EMBED + internal +#else + public +#endif + struct Duration { private readonly TimeSpan _timeSpan; private DurationType _durationType; @@ -669,12 +699,22 @@ public override string ToString() namespace ABI.Microsoft.UI.Xaml { - public static class CornerRadius +#if EMBED + internal +#else + public +#endif + static class CornerRadius { public static string GetGuidSignature() => $"struct(Microsoft.UI.Xaml.CornerRadius;f8;f8;f8;f8)"; } - public static class Duration +#if EMBED + internal +#else + public +#endif + static class Duration { public static string GetGuidSignature() { @@ -684,12 +724,22 @@ public static string GetGuidSignature() } } - public static class DurationType +#if EMBED + internal +#else + public +#endif + static class DurationType { public static string GetGuidSignature() => "enum(Microsoft.UI.Xaml.DurationType;i4)"; } - public static class GridLength +#if EMBED + internal +#else + public +#endif + static class GridLength { public static string GetGuidSignature() { @@ -698,12 +748,22 @@ public static string GetGuidSignature() } } - public static class GridUnitType +#if EMBED + internal +#else + public +#endif + static class GridUnitType { public static string GetGuidSignature() => "enum(Microsoft.UI.Xaml.GridUnitType;i4)"; } - public static class Thickness +#if EMBED + internal +#else + public +#endif + static class Thickness { public static string GetGuidSignature() => $"struct(Microsoft.UI.Xaml.Thickness;f8;f8;f8;f8)"; } diff --git a/src/cswinrt/strings/additions/Windows.Foundation/AsyncInfo.cs b/src/cswinrt/strings/additions/Windows.Foundation/AsyncInfo.cs index 25bff28ce..c43aaac31 100644 --- a/src/cswinrt/strings/additions/Windows.Foundation/AsyncInfo.cs +++ b/src/cswinrt/strings/additions/Windows.Foundation/AsyncInfo.cs @@ -15,10 +15,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// When an asynchronous operation created by this factory is actually started (by calling Start()), /// the specified Task-provider delegate will be invoked to create the Task that will /// be wrapped by the to-WinRT adapter.

-#if !NETSTANDARD2_0 - [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] +#if NET + [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif - public static class AsyncInfo +#if EMBED + internal +#else + public +#endif + static class AsyncInfo { #region Factory methods for creating "normal" IAsyncInfo instances backed by a Task created by a pastProvider delegate diff --git a/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncActionAdapter.cs b/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncActionAdapter.cs index 9fd47c158..9a3b96781 100644 --- a/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncActionAdapter.cs +++ b/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncActionAdapter.cs @@ -11,7 +11,7 @@ namespace System.Threading.Tasks using System.Threading.Tasks; using global::Windows.Foundation; -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif internal class TaskToAsyncActionAdapter diff --git a/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncActionWithProgressAdapter.cs b/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncActionWithProgressAdapter.cs index b4eff2cd4..85971aedd 100644 --- a/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncActionWithProgressAdapter.cs +++ b/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncActionWithProgressAdapter.cs @@ -11,7 +11,7 @@ namespace System.Threading.Tasks using System.Threading.Tasks; using global::Windows.Foundation; -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif internal class TaskToAsyncActionWithProgressAdapter diff --git a/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncInfoAdapter.cs b/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncInfoAdapter.cs index 75a71ac7c..47774514c 100644 --- a/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncInfoAdapter.cs +++ b/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncInfoAdapter.cs @@ -18,7 +18,7 @@ namespace System.Threading.Tasks /// Implements a wrapper that allows to expose managed System.Threading.Tasks.Task objects as /// through the WinRT Windows.Foundation.IAsyncInfo interface. /// -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif internal class TaskToAsyncInfoAdapter diff --git a/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncOperationAdapter.cs b/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncOperationAdapter.cs index eee822ecb..23c216c1d 100644 --- a/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncOperationAdapter.cs +++ b/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncOperationAdapter.cs @@ -12,7 +12,7 @@ namespace System.Threading.Tasks using System.Threading.Tasks; using global::Windows.Foundation; -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif internal class TaskToAsyncOperationAdapter diff --git a/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncOperationWithProgressAdapter.cs b/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncOperationWithProgressAdapter.cs index a5b582854..450497719 100644 --- a/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncOperationWithProgressAdapter.cs +++ b/src/cswinrt/strings/additions/Windows.Foundation/TaskToAsyncOperationWithProgressAdapter.cs @@ -12,7 +12,7 @@ namespace System.Threading.Tasks using System.Threading.Tasks; using global::Windows.Foundation; -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif internal class TaskToAsyncOperationWithProgressAdapter diff --git a/src/cswinrt/strings/additions/Windows.Foundation/Windows.Foundation.SR.cs b/src/cswinrt/strings/additions/Windows.Foundation/Windows.Foundation.SR.cs index 8126e3645..fd5b613bb 100644 --- a/src/cswinrt/strings/additions/Windows.Foundation/Windows.Foundation.SR.cs +++ b/src/cswinrt/strings/additions/Windows.Foundation/Windows.Foundation.SR.cs @@ -4,6 +4,9 @@ namespace Windows.Foundation { +#if EMBED + internal +#endif class SR { public static string Argument_BufferLengthExceedsCapacity = "The specified useful data length exceeds the capacity of this buffer."; diff --git a/src/cswinrt/strings/additions/Windows.Foundation/Windows.Foundation.cs b/src/cswinrt/strings/additions/Windows.Foundation/Windows.Foundation.cs index 6ff035b8d..8a1fa8ede 100644 --- a/src/cswinrt/strings/additions/Windows.Foundation/Windows.Foundation.cs +++ b/src/cswinrt/strings/additions/Windows.Foundation/Windows.Foundation.cs @@ -11,7 +11,12 @@ namespace System #if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif - public static class WindowsRuntimeSystemExtensions +#if EMBED + internal +#else + public +#endif + static class WindowsRuntimeSystemExtensions { public static Task AsTask(this IAsyncAction source, CancellationToken cancellationToken) { diff --git a/src/cswinrt/strings/additions/Windows.Storage.Streams/IBufferByteAccess.cs b/src/cswinrt/strings/additions/Windows.Storage.Streams/IBufferByteAccess.cs index a25cad1eb..2b86bac62 100644 --- a/src/cswinrt/strings/additions/Windows.Storage.Streams/IBufferByteAccess.cs +++ b/src/cswinrt/strings/additions/Windows.Storage.Streams/IBufferByteAccess.cs @@ -17,7 +17,7 @@ namespace ABI.Windows.Storage.Streams using global::System.Runtime.InteropServices; using global::System.ComponentModel; -#if NETSTANDARD2_0 +#if !NET [global::WinRT.ObjectReferenceWrapper(nameof(_obj)), EditorBrowsable(EditorBrowsableState.Never)] [Guid("905a0fef-bc53-11df-8c49-001e4fc686da")] internal unsafe class IBufferByteAccess : global::Windows.Storage.Streams.IBufferByteAccess diff --git a/src/cswinrt/strings/additions/Windows.Storage.Streams/IMarshal.cs b/src/cswinrt/strings/additions/Windows.Storage.Streams/IMarshal.cs index bca5115ad..d56dc3d2e 100644 --- a/src/cswinrt/strings/additions/Windows.Storage.Streams/IMarshal.cs +++ b/src/cswinrt/strings/additions/Windows.Storage.Streams/IMarshal.cs @@ -37,7 +37,7 @@ public unsafe struct Vftbl { internal global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; -#if NETSTANDARD2_0 +#if !NET private void* _GetUnmarshalClass_0; public delegate* unmanaged[Stdcall] GetUnmarshalClass_0 { get => (delegate* unmanaged[Stdcall])_GetUnmarshalClass_0; set => _GetUnmarshalClass_0 = value; } private void* _GetMarshalSizeMax_1; @@ -66,7 +66,7 @@ public unsafe struct Vftbl static Vftbl() { -#if NETSTANDARD2_0 +#if !NET AbiToProjectionVftable = new Vftbl { IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, @@ -94,7 +94,7 @@ static Vftbl() #endif } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int Do_Abi_GetUnmarshalClass_0(IntPtr thisPtr, Guid* riid, IntPtr pv, global::Com.MSHCTX dwDestContext, IntPtr pvDestContext, global::Com.MSHLFLAGS mshlFlags, Guid* pCid) @@ -111,7 +111,7 @@ private static int Do_Abi_GetUnmarshalClass_0(IntPtr thisPtr, Guid* riid, IntPtr return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int Do_Abi_GetMarshalSizeMax_1(IntPtr thisPtr, Guid* riid, IntPtr pv, global::Com.MSHCTX dwDestContext, IntPtr pvDestContext, global::Com.MSHLFLAGS mshlflags, uint* pSize) @@ -128,7 +128,7 @@ private static int Do_Abi_GetMarshalSizeMax_1(IntPtr thisPtr, Guid* riid, IntPtr return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int Do_Abi_MarshalInterface_2(IntPtr thisPtr, IntPtr pStm, Guid* riid, IntPtr pv, global::Com.MSHCTX dwDestContext, IntPtr pvDestContext, global::Com.MSHLFLAGS mshlflags) @@ -144,7 +144,7 @@ private static int Do_Abi_MarshalInterface_2(IntPtr thisPtr, IntPtr pStm, Guid* return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int Do_Abi_UnmarshalInterface_3(IntPtr thisPtr, IntPtr pStm, Guid* riid, IntPtr* ppv) @@ -161,7 +161,7 @@ private static int Do_Abi_UnmarshalInterface_3(IntPtr thisPtr, IntPtr pStm, Guid return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int Do_Abi_ReleaseMarshalData_4(IntPtr thisPtr, IntPtr pStm) @@ -177,7 +177,7 @@ private static int Do_Abi_ReleaseMarshalData_4(IntPtr thisPtr, IntPtr pStm) return 0; } -#if !NETSTANDARD2_0 +#if NET [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int Do_Abi_DisconnectObject_5(IntPtr thisPtr, uint dwReserved) diff --git a/src/cswinrt/strings/additions/Windows.Storage.Streams/NetFxToWinRtStreamAdapter.cs b/src/cswinrt/strings/additions/Windows.Storage.Streams/NetFxToWinRtStreamAdapter.cs index 6336e178f..90fe7be96 100644 --- a/src/cswinrt/strings/additions/Windows.Storage.Streams/NetFxToWinRtStreamAdapter.cs +++ b/src/cswinrt/strings/additions/Windows.Storage.Streams/NetFxToWinRtStreamAdapter.cs @@ -224,7 +224,7 @@ void IDisposable.Dispose() #region IInputStream public interface -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif public IAsyncOperationWithProgress ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) @@ -289,7 +289,7 @@ public IAsyncOperationWithProgress ReadAsync(IBuffer buffer, uint #region IOutputStream public interface -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif public IAsyncOperationWithProgress WriteAsync(IBuffer buffer) @@ -311,7 +311,7 @@ public IAsyncOperationWithProgress WriteAsync(IBuffer buffer) return StreamOperationsImplementation.WriteAsync_AbstractStream(str, buffer); } -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif public IAsyncOperation FlushAsync() diff --git a/src/cswinrt/strings/additions/Windows.Storage.Streams/StreamOperationsImplementation.cs b/src/cswinrt/strings/additions/Windows.Storage.Streams/StreamOperationsImplementation.cs index cffe81635..b14a652a5 100644 --- a/src/cswinrt/strings/additions/Windows.Storage.Streams/StreamOperationsImplementation.cs +++ b/src/cswinrt/strings/additions/Windows.Storage.Streams/StreamOperationsImplementation.cs @@ -21,7 +21,7 @@ namespace Windows.Storage.Streams /// Moreover, knowledge about the actual runtime type of the IBuffer can also help choosing the optimal /// implementation. This type provides static methods that encapsulate the performance logic and can be used /// by NetFxToWinRtStreamAdapter. -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif internal static class StreamOperationsImplementation diff --git a/src/cswinrt/strings/additions/Windows.Storage.Streams/WinRtToNetFxStreamAdapter.cs b/src/cswinrt/strings/additions/Windows.Storage.Streams/WinRtToNetFxStreamAdapter.cs index 6137e5553..fe410f4a6 100644 --- a/src/cswinrt/strings/additions/Windows.Storage.Streams/WinRtToNetFxStreamAdapter.cs +++ b/src/cswinrt/strings/additions/Windows.Storage.Streams/WinRtToNetFxStreamAdapter.cs @@ -392,7 +392,7 @@ public override void SetLength(long value) #region Reading -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif private IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool usedByBlockingWrapper) @@ -498,7 +498,7 @@ public override int EndRead(IAsyncResult asyncResult) } } -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) @@ -525,7 +525,7 @@ public override Task ReadAsync(byte[] buffer, int offset, int count, Cancel return ReadAsyncInternal(buffer, offset, count, cancellationToken); } -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif public override int Read(byte[] buffer, int offset, int count) @@ -537,7 +537,7 @@ public override int Read(byte[] buffer, int offset, int count) return bytesread; } -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif public override int ReadByte() @@ -639,7 +639,7 @@ public override void EndWrite(IAsyncResult asyncResult) } } -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) @@ -738,7 +738,7 @@ public override void Flush() } } -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif public override Task FlushAsync(CancellationToken cancellationToken) @@ -765,7 +765,7 @@ public override Task FlushAsync(CancellationToken cancellationToken) // Moved it to the end while using Dev10 VS because it does not understand async and everything that follows looses intellisense. // Should move this code into the Reading regios once using Dev11 VS becomes the norm. -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] #endif private async Task ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/cswinrt/strings/additions/Windows.Storage.Streams/WindowsRuntimeBuffer.cs b/src/cswinrt/strings/additions/Windows.Storage.Streams/WindowsRuntimeBuffer.cs index fc881a400..fb448ca70 100644 --- a/src/cswinrt/strings/additions/Windows.Storage.Streams/WindowsRuntimeBuffer.cs +++ b/src/cswinrt/strings/additions/Windows.Storage.Streams/WindowsRuntimeBuffer.cs @@ -18,7 +18,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// Contains an implementation of the WinRT IBuffer interface that conforms to all requirements on classes that implement that interface, /// such as implementing additional interfaces. /// - public sealed class WindowsRuntimeBuffer : IBuffer, IBufferByteAccess, IMarshal +#if EMBED + internal +#else + public +#endif + sealed class WindowsRuntimeBuffer : IBuffer, IBufferByteAccess, IMarshal { [DllImport("api-ms-win-core-winrt-robuffer-l1-1-0.dll")] private static extern int RoGetBufferMarshaler(out IntPtr bufferMarshalerPtr); diff --git a/src/cswinrt/strings/additions/Windows.Storage.Streams/WindowsRuntimeBufferExtensions.cs b/src/cswinrt/strings/additions/Windows.Storage.Streams/WindowsRuntimeBufferExtensions.cs index 783ecc665..b069cd3e9 100644 --- a/src/cswinrt/strings/additions/Windows.Storage.Streams/WindowsRuntimeBufferExtensions.cs +++ b/src/cswinrt/strings/additions/Windows.Storage.Streams/WindowsRuntimeBufferExtensions.cs @@ -13,9 +13,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// /// Contains extension methods that expose operations on WinRT Windows.Foundation.IBuffer. /// - public static class WindowsRuntimeBufferExtensions +#if EMBED + internal +#else + public +#endif + static class WindowsRuntimeBufferExtensions { - #region (Byte []).AsBuffer extensions +#region (Byte []).AsBuffer extensions public static IBuffer AsBuffer(this byte[] source) { @@ -49,10 +54,10 @@ public static IBuffer AsBuffer(this byte[] source, int offset, int length, int c return new WindowsRuntimeBuffer(source, offset, length, capacity); } - #endregion (Byte []).AsBuffer extensions +#endregion (Byte []).AsBuffer extensions - #region (Byte []).CopyTo extensions for copying to an (IBuffer) +#region (Byte []).CopyTo extensions for copying to an (IBuffer) /// /// Copies the contents of source to destination starting at offset 0. @@ -104,10 +109,10 @@ public static void CopyTo(this byte[] source, int sourceIndex, IBuffer destinati Marshal.Copy(source, sourceIndex, destPtr, count); } - #endregion (Byte []).CopyTo extensions for copying to an (IBuffer) +#endregion (Byte []).CopyTo extensions for copying to an (IBuffer) - #region (IBuffer).ToArray extensions for copying to a new (Byte []) +#region (IBuffer).ToArray extensions for copying to a new (Byte []) public static byte[] ToArray(this IBuffer source) { @@ -132,10 +137,10 @@ public static byte[] ToArray(this IBuffer source, uint sourceIndex, int count) return destination; } - #endregion (IBuffer).ToArray extensions for copying to a new (Byte []) +#endregion (IBuffer).ToArray extensions for copying to a new (Byte []) - #region (IBuffer).CopyTo extensions for copying to a (Byte []) +#region (IBuffer).CopyTo extensions for copying to a (Byte []) public static void CopyTo(this IBuffer source, byte[] destination) { @@ -171,10 +176,10 @@ public static void CopyTo(this IBuffer source, uint sourceIndex, byte[] destinat Marshal.Copy(srcPtr, destination, destinationIndex, count); } - #endregion (IBuffer).CopyTo extensions for copying to a (Byte []) +#endregion (IBuffer).CopyTo extensions for copying to a (Byte []) - #region (IBuffer).CopyTo extensions for copying to an (IBuffer) +#region (IBuffer).CopyTo extensions for copying to an (IBuffer) public static void CopyTo(this IBuffer source, IBuffer destination) { @@ -239,10 +244,10 @@ public static void CopyTo(this IBuffer source, uint sourceIndex, IBuffer destina MemCopy(srcPtr, destPtr, count); } - #endregion (IBuffer).CopyTo extensions for copying to an (IBuffer) +#endregion (IBuffer).CopyTo extensions for copying to an (IBuffer) - #region Access to underlying array optimised for IBuffers backed by managed arrays (to avoid pinning) +#region Access to underlying array optimised for IBuffers backed by managed arrays (to avoid pinning) /// /// If the specified IBuffer is backed by a managed array, this method will return true and @@ -317,10 +322,10 @@ public static bool IsSameData(this IBuffer buffer, IBuffer otherBuffer) } } - #endregion Access to underlying array optimised for IBuffers backed by managed arrays (to avoid pinning) +#endregion Access to underlying array optimised for IBuffers backed by managed arrays (to avoid pinning) - #region Extensions for co-operation with memory streams (share mem stream data; expose data as managed/unmanaged mem stream) +#region Extensions for co-operation with memory streams (share mem stream data; expose data as managed/unmanaged mem stream) /// /// Creates a new IBuffer instance backed by the same memory as is backing the specified MemoryStream. /// The MemoryStream may re-sized in future, as a result the stream will be backed by a different memory region. @@ -416,10 +421,10 @@ public static Stream AsStream(this IBuffer source) } } - #endregion Extensions for co-operation with memory streams (share mem stream data; expose data as managed/unmanaged mem stream) +#endregion Extensions for co-operation with memory streams (share mem stream data; expose data as managed/unmanaged mem stream) - #region Extensions for direct by-offset access to buffer data elements +#region Extensions for direct by-offset access to buffer data elements public static byte GetByte(this IBuffer source, uint byteOffset) { @@ -442,10 +447,10 @@ public static byte GetByte(this IBuffer source, uint byteOffset) } } - #endregion Extensions for direct by-offset access to buffer data elements +#endregion Extensions for direct by-offset access to buffer data elements - #region Private plumbing +#region Private plumbing private class WindowsRuntimeBufferUnmanagedMemoryStream : UnmanagedMemoryStream { @@ -496,7 +501,7 @@ private static unsafe void MemCopy(IntPtr src, IntPtr dst, uint count) Marshal.Copy(tmp, 0, dst, bCount); return; } - #endregion Private plumbing +#endregion Private plumbing } // class WindowsRuntimeBufferExtensions } // namespace diff --git a/src/cswinrt/strings/additions/Windows.Storage.Streams/WindowsRuntimeStreamExtensions.cs b/src/cswinrt/strings/additions/Windows.Storage.Streams/WindowsRuntimeStreamExtensions.cs index 278da7b2b..e13d067d1 100644 --- a/src/cswinrt/strings/additions/Windows.Storage.Streams/WindowsRuntimeStreamExtensions.cs +++ b/src/cswinrt/strings/additions/Windows.Storage.Streams/WindowsRuntimeStreamExtensions.cs @@ -17,7 +17,12 @@ namespace System.IO /// Contains extension methods for conversion between WinRT streams and managed streams. /// This class is the public facade for the stream adapters library. /// - public static class WindowsRuntimeStreamExtensions +#if EMBED + internal +#else + public +#endif + static class WindowsRuntimeStreamExtensions { #region Constants and static Fields @@ -32,7 +37,7 @@ private static readonly ConditionalWeakTable #endregion Constants and static Fields -#if !NETSTANDARD2_0 +#if NET #region Helpers diff --git a/src/cswinrt/strings/additions/Windows.Storage/IStorageFolderHandleAccess.cs b/src/cswinrt/strings/additions/Windows.Storage/IStorageFolderHandleAccess.cs index 084fb726b..6d53313de 100644 --- a/src/cswinrt/strings/additions/Windows.Storage/IStorageFolderHandleAccess.cs +++ b/src/cswinrt/strings/additions/Windows.Storage/IStorageFolderHandleAccess.cs @@ -26,7 +26,7 @@ namespace ABI.Windows.Storage using global::System; using global::System.ComponentModel; -#if NETSTANDARD2_0 +#if !NET [global::WinRT.ObjectReferenceWrapper(nameof(_obj)), EditorBrowsable(EditorBrowsableState.Never)] [Guid("DF19938F-5462-48A0-BE65-D2A3271A08D6")] internal unsafe class IStorageFolderHandleAccess : global::Windows.Storage.IStorageFolderHandleAccess diff --git a/src/cswinrt/strings/additions/Windows.Storage/IStorageItemHandleAccess.cs b/src/cswinrt/strings/additions/Windows.Storage/IStorageItemHandleAccess.cs index 468a08141..a797f91f2 100644 --- a/src/cswinrt/strings/additions/Windows.Storage/IStorageItemHandleAccess.cs +++ b/src/cswinrt/strings/additions/Windows.Storage/IStorageItemHandleAccess.cs @@ -22,7 +22,7 @@ namespace ABI.Windows.Storage using global::Microsoft.Win32.SafeHandles; using global::System.ComponentModel; -#if NETSTANDARD2_0 +#if !NET [global::WinRT.ObjectReferenceWrapper(nameof(_obj)), EditorBrowsable(EditorBrowsableState.Never)] [Guid("5CA296B2-2C25-4D22-B785-B885C8201E6A")] internal unsafe class IStorageItemHandleAccess : global::Windows.Storage.IStorageItemHandleAccess diff --git a/src/cswinrt/strings/additions/Windows.Storage/WindowsRuntimeStorageExtensions.cs b/src/cswinrt/strings/additions/Windows.Storage/WindowsRuntimeStorageExtensions.cs index 855d2b9b9..eb6837849 100644 --- a/src/cswinrt/strings/additions/Windows.Storage/WindowsRuntimeStorageExtensions.cs +++ b/src/cswinrt/strings/additions/Windows.Storage/WindowsRuntimeStorageExtensions.cs @@ -11,14 +11,19 @@ namespace System.IO using global::Windows.Storage.FileProperties; using global::Windows.Storage.Streams; using System.Runtime.InteropServices; - + /// /// Contains extension methods that provide convenience helpers for WinRT IO. /// - public static class WindowsRuntimeStorageExtensions +#if EMBED + internal +#else + public +#endif + static class WindowsRuntimeStorageExtensions { // Net5-specific extension methods -#if !NETSTANDARD2_0 +#if NET [global::System.Runtime.Versioning.SupportedOSPlatform("windows10.0.10240.0")] public static Task OpenStreamForReadAsync(this IStorageFile windowsRuntimeFile) { diff --git a/src/cswinrt/strings/additions/Windows.UI/Windows.UI.cs b/src/cswinrt/strings/additions/Windows.UI/Windows.UI.cs index e3de81955..913b030a4 100644 --- a/src/cswinrt/strings/additions/Windows.UI/Windows.UI.cs +++ b/src/cswinrt/strings/additions/Windows.UI/Windows.UI.cs @@ -6,7 +6,12 @@ namespace Windows.UI [global::WinRT.WindowsRuntimeType("Windows.Foundation.UniversalApiContract")] [StructLayout(LayoutKind.Sequential)] - public struct Color : IFormattable +#if EMBED + internal +#else + public +#endif + struct Color : IFormattable { private byte _A; private byte _R; @@ -124,7 +129,12 @@ public bool Equals(Color color) namespace ABI.Windows.UI { - public static class Color +#if EMBED + internal +#else + public +#endif + static class Color { public static string GetGuidSignature() { From 87b2f568e14beac27e6786d49301d5180ef5aa68 Mon Sep 17 00:00:00 2001 From: Joshua Larkin <70237359+j0shuams@users.noreply.github.com> Date: Mon, 4 Oct 2021 11:28:55 -0700 Subject: [PATCH 04/11] cut --- src/cswinrt/code_writers.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cswinrt/code_writers.h b/src/cswinrt/code_writers.h index 22fdaa3c5..6bbd9d119 100644 --- a/src/cswinrt/code_writers.h +++ b/src/cswinrt/code_writers.h @@ -2526,7 +2526,7 @@ db_path.stem().string()); }; void write_static_class(writer& w, TypeDef const& type) - { // maybe + { w.write(R"(%%% static class % { %})", @@ -4939,7 +4939,7 @@ IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, bind(type), bind(type), bind(type, false), - is_exclusive_to(type) || (is_projection_internal(type) || settings.embedded) ? "internal" : "public", // + is_exclusive_to(type) || (is_projection_internal(type) || settings.embedded) ? "internal" : "public", type_name, bind(type, object_type{}, false, false), bind(type) From 29b4340aa78a01d88ec20b1314907fea99712fd2 Mon Sep 17 00:00:00 2001 From: Joshua Larkin <70237359+j0shuams@users.noreply.github.com> Date: Tue, 12 Oct 2021 15:17:41 -0700 Subject: [PATCH 05/11] feedback --- src/WinRT.Runtime/AgileReference.cs | 30 ++-------- .../ComWrappersSupport.netstandard2.0.cs | 10 +--- src/WinRT.Runtime/Projections/Geometry.cs | 56 ++++++++++++++++--- .../Projections/IDictionary.netstandard2.0.cs | 3 - 4 files changed, 54 insertions(+), 45 deletions(-) diff --git a/src/WinRT.Runtime/AgileReference.cs b/src/WinRT.Runtime/AgileReference.cs index 6b2831e85..e7e78e091 100644 --- a/src/WinRT.Runtime/AgileReference.cs +++ b/src/WinRT.Runtime/AgileReference.cs @@ -17,12 +17,7 @@ class AgileReference : IDisposable private readonly IntPtr _cookie; private bool disposed; - #if EMBED - internal -#else - public -#endif - unsafe AgileReference(IObjectReference instance) + public unsafe AgileReference(IObjectReference instance) { if(instance?.ThisPtr == null) { @@ -53,13 +48,7 @@ unsafe AgileReference(IObjectReference instance) MarshalInterface.DisposeAbi(agileReference); } } - -#if EMBED - internal -#else - public -#endif - IObjectReference Get() => _cookie == IntPtr.Zero ? _agileReference?.Resolve(typeof(IUnknownVftbl).GUID) : Git.Value?.GetInterfaceFromGlobal(_cookie, typeof(IUnknownVftbl).GUID); + public IObjectReference Get() => _cookie == IntPtr.Zero ? _agileReference?.Resolve(typeof(IUnknownVftbl).GUID) : Git.Value?.GetInterfaceFromGlobal(_cookie, typeof(IUnknownVftbl).GUID); protected virtual void Dispose(bool disposing) { @@ -122,23 +111,12 @@ public void Dispose() sealed class AgileReference : AgileReference where T : class { - -#if EMBED - internal -#else - public -#endif - unsafe AgileReference(IObjectReference instance) + public unsafe AgileReference(IObjectReference instance) : base(instance) { } -#if EMBED - internal -#else - public -#endif - new T Get() + public new T Get() { using var objRef = base.Get(); return ComWrappersSupport.CreateRcwForComObject(objRef?.ThisPtr ?? IntPtr.Zero); diff --git a/src/WinRT.Runtime/ComWrappersSupport.netstandard2.0.cs b/src/WinRT.Runtime/ComWrappersSupport.netstandard2.0.cs index 808af8244..3cc5e9d9f 100644 --- a/src/WinRT.Runtime/ComWrappersSupport.netstandard2.0.cs +++ b/src/WinRT.Runtime/ComWrappersSupport.netstandard2.0.cs @@ -273,18 +273,12 @@ private static Func CreateFactoryForImplementationType(str } -#if EMBED - internal -#endif struct ComInterfaceEntry { public IntPtr Vtable; public Guid IID; } -#if EMBED - internal -#endif struct UnmanagedObject { public IntPtr _vftblPtr; @@ -296,10 +290,10 @@ internal static T FindObject(IntPtr thisPtr) GCHandle thisHandle = GCHandle.FromIntPtr(unmanagedObject._gchandlePtr); return (T)thisHandle.Target; } - } + } internal class ComCallableWrapper - { + { private Dictionary _managedQITable; private GCHandle _qiTableHandle; private volatile IntPtr _strongHandle; diff --git a/src/WinRT.Runtime/Projections/Geometry.cs b/src/WinRT.Runtime/Projections/Geometry.cs index 5b64fbc3d..a25b1791c 100644 --- a/src/WinRT.Runtime/Projections/Geometry.cs +++ b/src/WinRT.Runtime/Projections/Geometry.cs @@ -11,7 +11,12 @@ internal class GSR [global::WinRT.WindowsRuntimeType("Windows.Foundation.FoundationContract")] [StructLayout(LayoutKind.Sequential)] - public struct Point : IFormattable +#if EMBED + internal +#else + public +#endif + struct Point : IFormattable { public float _x; public float _y; @@ -98,7 +103,12 @@ public override int GetHashCode() [global::WinRT.WindowsRuntimeType("Windows.Foundation.FoundationContract")] [StructLayout(LayoutKind.Sequential)] - public struct Rect : IFormattable +#if EMBED + internal +#else + public +#endif + struct Rect : IFormattable { public float _x; public float _y; @@ -417,7 +427,12 @@ public override int GetHashCode() [global::WinRT.WindowsRuntimeType("Windows.Foundation.FoundationContract")] [StructLayout(LayoutKind.Sequential)] - public struct Size +#if EMBED + internal +#else + public +#endif + struct Size { public float _width; public float _height; @@ -540,7 +555,12 @@ public override string ToString() } } - public static class TokenizerHelper +#if EMBED + internal +#else + public +#endif + static class TokenizerHelper { public static char GetNumericListSeparator(IFormatProvider provider) { @@ -565,7 +585,12 @@ public static char GetNumericListSeparator(IFormatProvider provider) namespace ABI.Windows.Foundation { - public static class Point +#if EMBED + internal +#else + public +#endif + static class Point { public static string GetGuidSignature() { @@ -573,7 +598,12 @@ public static string GetGuidSignature() } } - public static class Rect +#if EMBED + internal +#else + public +#endif + static class Rect { public static string GetGuidSignature() { @@ -581,7 +611,12 @@ public static string GetGuidSignature() } } - public static class Size +#if EMBED + internal +#else + public +#endif + static class Size { public static string GetGuidSignature() { @@ -592,7 +627,12 @@ public static string GetGuidSignature() namespace System.Numerics { - public static class VectorExtensions +#if EMBED + internal +#else + public +#endif + static class VectorExtensions { public static global::Windows.Foundation.Point ToPoint(this Vector2 vector) { diff --git a/src/WinRT.Runtime/Projections/IDictionary.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IDictionary.netstandard2.0.cs index 016a1d4ef..ab8fbbfad 100644 --- a/src/WinRT.Runtime/Projections/IDictionary.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IDictionary.netstandard2.0.cs @@ -15,9 +15,6 @@ namespace Windows.Foundation.Collections { [Guid("3C2925FE-8519-45C1-AA79-197B6718C1C1")] -#if EMBED - internal -#endif interface IMap : IIterable> { V Lookup(K key); From 2db8218fe488da20dcde4af930db8a48c26fce6b Mon Sep 17 00:00:00 2001 From: Joshua Larkin <70237359+j0shuams@users.noreply.github.com> Date: Tue, 12 Oct 2021 15:26:25 -0700 Subject: [PATCH 06/11] cut --- src/WinRT.Runtime/CastExtensions.cs | 14 ++------------ src/WinRT.Runtime/Directory.Build.targets | 1 - 2 files changed, 2 insertions(+), 13 deletions(-) diff --git a/src/WinRT.Runtime/CastExtensions.cs b/src/WinRT.Runtime/CastExtensions.cs index 55faaebc5..a41df4333 100644 --- a/src/WinRT.Runtime/CastExtensions.cs +++ b/src/WinRT.Runtime/CastExtensions.cs @@ -23,12 +23,7 @@ static class CastExtensions /// Otherwise, creates a new wrapper of the underlying WinRT object that implements . /// /// Thrown if the runtime type of is not a projected type (if the object is a managed object). -#if EMBED - internal -#else - public -#endif - static TInterface As(this object value) + public static TInterface As(this object value) { if (typeof(TInterface) == typeof(object)) { @@ -63,12 +58,7 @@ static TInterface As(this object value) /// Otherwise, returns null. /// /// Thrown if the runtime type of is not a projected type. -#if EMBED - internal -#else - public -#endif - static AgileReference AsAgile(this T value) where T : class + public static AgileReference AsAgile(this T value) where T : class { if(value == null) { diff --git a/src/WinRT.Runtime/Directory.Build.targets b/src/WinRT.Runtime/Directory.Build.targets index 5e547527b..c4c20d0a7 100644 --- a/src/WinRT.Runtime/Directory.Build.targets +++ b/src/WinRT.Runtime/Directory.Build.targets @@ -8,5 +8,4 @@ Copyright (C) Microsoft Corporation. All rights reserved. - \ No newline at end of file From 023bfb78f2b572c0a50b57e2f93c63a170c7db07 Mon Sep 17 00:00:00 2001 From: Joshua Larkin <70237359+j0shuams@users.noreply.github.com> Date: Tue, 12 Oct 2021 16:35:00 -0700 Subject: [PATCH 07/11] internal --- src/WinRT.Runtime/ComWrappersSupport.net5.cs | 2 + src/WinRT.Runtime/ExceptionHelpers.cs | 1 - .../Interop/IActivationFactory.cs | 7 +- .../Interop/IAgileReference.net5.cs | 7 +- src/WinRT.Runtime/Interop/IUnknownVftbl.cs | 7 +- .../Interop/StandardDelegates.cs | 210 +++++++++++++++--- .../Projections/IDictionary.net5.cs | 7 +- .../Projections/IDisposable.net5.cs | 7 +- .../Projections/IEnumerable.net5.cs | 19 +- src/WinRT.Runtime/Projections/IList.net5.cs | 8 +- .../Projections/IReadOnlyDictionary.net5.cs | 8 +- .../Projections/IReadOnlyList.net5.cs | 7 +- .../IReadOnlyList.netstandard2.0.cs | 4 +- src/WinRT.Runtime/Projections/Numerics.cs | 49 +++- src/WinRT.Runtime/Projections/SystemTypes.cs | 21 +- src/WinRT.Runtime/Projections/Type.cs | 11 +- 16 files changed, 316 insertions(+), 59 deletions(-) diff --git a/src/WinRT.Runtime/ComWrappersSupport.net5.cs b/src/WinRT.Runtime/ComWrappersSupport.net5.cs index 953a69345..8a0ced005 100644 --- a/src/WinRT.Runtime/ComWrappersSupport.net5.cs +++ b/src/WinRT.Runtime/ComWrappersSupport.net5.cs @@ -214,6 +214,7 @@ private static Func CreateFactoryForImplementationType(str parms).Compile(); } } + #if EMBED internal #else @@ -367,6 +368,7 @@ public unsafe static void Init(IObjectReference objRef, bool addRefFromTrackerSo } } } + #if EMBED internal #else diff --git a/src/WinRT.Runtime/ExceptionHelpers.cs b/src/WinRT.Runtime/ExceptionHelpers.cs index 8410fa023..14448224b 100644 --- a/src/WinRT.Runtime/ExceptionHelpers.cs +++ b/src/WinRT.Runtime/ExceptionHelpers.cs @@ -436,7 +436,6 @@ namespace Automation #else public #endif - class ElementNotAvailableException : Exception { public ElementNotAvailableException() diff --git a/src/WinRT.Runtime/Interop/IActivationFactory.cs b/src/WinRT.Runtime/Interop/IActivationFactory.cs index d9c674022..0026c8ce6 100644 --- a/src/WinRT.Runtime/Interop/IActivationFactory.cs +++ b/src/WinRT.Runtime/Interop/IActivationFactory.cs @@ -9,7 +9,12 @@ namespace WinRT.Interop { [WindowsRuntimeType] [Guid("00000035-0000-0000-C000-000000000046")] - public interface IActivationFactory +#if EMBED + internal +#else + public +#endif + interface IActivationFactory { IntPtr ActivateInstance(); } diff --git a/src/WinRT.Runtime/Interop/IAgileReference.net5.cs b/src/WinRT.Runtime/Interop/IAgileReference.net5.cs index 63f699b68..ca96b7bb9 100644 --- a/src/WinRT.Runtime/Interop/IAgileReference.net5.cs +++ b/src/WinRT.Runtime/Interop/IAgileReference.net5.cs @@ -14,7 +14,12 @@ internal interface IAgileReference [WindowsRuntimeType] [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] - public interface IAgileObject +#if EMBED + internal +#else + public +#endif + interface IAgileObject { public static readonly Guid IID = Guid.Parse("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90"); } diff --git a/src/WinRT.Runtime/Interop/IUnknownVftbl.cs b/src/WinRT.Runtime/Interop/IUnknownVftbl.cs index 8a81c4c0a..3612b05cc 100644 --- a/src/WinRT.Runtime/Interop/IUnknownVftbl.cs +++ b/src/WinRT.Runtime/Interop/IUnknownVftbl.cs @@ -6,7 +6,12 @@ namespace WinRT.Interop { [Guid("00000000-0000-0000-C000-000000000046")] - public unsafe struct IUnknownVftbl +#if EMBED + internal +#else + public +#endif + unsafe struct IUnknownVftbl { private void* _QueryInterface; public delegate* unmanaged[Stdcall] QueryInterface { get => (delegate* unmanaged[Stdcall])_QueryInterface; set => _QueryInterface = (void*)value; } diff --git a/src/WinRT.Runtime/Interop/StandardDelegates.cs b/src/WinRT.Runtime/Interop/StandardDelegates.cs index 02bdd6439..be8f9c06e 100644 --- a/src/WinRT.Runtime/Interop/StandardDelegates.cs +++ b/src/WinRT.Runtime/Interop/StandardDelegates.cs @@ -7,65 +7,215 @@ namespace WinRT.Interop { // standard accessors/mutators [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsBoolean(IntPtr thisPtr, out byte value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsBoolean(IntPtr thisPtr, out byte value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsBoolean(IntPtr thisPtr, byte value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsBoolean(IntPtr thisPtr, byte value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsChar(IntPtr thisPtr, out ushort value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsChar(IntPtr thisPtr, out ushort value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsChar(IntPtr thisPtr, ushort value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsChar(IntPtr thisPtr, ushort value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsSByte(IntPtr thisPtr, out sbyte value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsSByte(IntPtr thisPtr, out sbyte value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsSByte(IntPtr thisPtr, sbyte value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsSByte(IntPtr thisPtr, sbyte value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsByte(IntPtr thisPtr, out byte value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsByte(IntPtr thisPtr, out byte value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsByte(IntPtr thisPtr, byte value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsByte(IntPtr thisPtr, byte value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsInt16(IntPtr thisPtr, out short value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsInt16(IntPtr thisPtr, out short value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsInt16(IntPtr thisPtr, short value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsInt16(IntPtr thisPtr, short value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsUInt16(IntPtr thisPtr, out ushort value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsUInt16(IntPtr thisPtr, out ushort value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsUInt16(IntPtr thisPtr, ushort value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsUInt16(IntPtr thisPtr, ushort value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsInt32(IntPtr thisPtr, out int value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsInt32(IntPtr thisPtr, out int value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsInt32(IntPtr thisPtr, int value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsInt32(IntPtr thisPtr, int value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsUInt32(IntPtr thisPtr, out uint value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsUInt32(IntPtr thisPtr, out uint value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsUInt32(IntPtr thisPtr, uint value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsUInt32(IntPtr thisPtr, uint value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsInt64(IntPtr thisPtr, out long value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsInt64(IntPtr thisPtr, out long value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsInt64(IntPtr thisPtr, long value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsInt64(IntPtr thisPtr, long value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsUInt64(IntPtr thisPtr, out ulong value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsUInt64(IntPtr thisPtr, out ulong value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsUInt64(IntPtr thisPtr, ulong value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsUInt64(IntPtr thisPtr, ulong value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsFloat(IntPtr thisPtr, out float value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsFloat(IntPtr thisPtr, out float value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsFloat(IntPtr thisPtr, float value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsFloat(IntPtr thisPtr, float value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsDouble(IntPtr thisPtr, out double value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsDouble(IntPtr thisPtr, out double value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsDouble(IntPtr thisPtr, double value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsDouble(IntPtr thisPtr, double value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsObject(IntPtr thisPtr, out IntPtr value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsObject(IntPtr thisPtr, out IntPtr value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsObject(IntPtr thisPtr, IntPtr value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsObject(IntPtr thisPtr, IntPtr value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsGuid(IntPtr thisPtr, out Guid value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsGuid(IntPtr thisPtr, out Guid value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsGuid(IntPtr thisPtr, Guid value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsGuid(IntPtr thisPtr, Guid value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _get_PropertyAsString(IntPtr thisPtr, out IntPtr value); +#if EMBED + internal +#else + public +#endif + delegate int _get_PropertyAsString(IntPtr thisPtr, out IntPtr value); [EditorBrowsable(EditorBrowsableState.Never)] - public delegate int _put_PropertyAsString(IntPtr thisPtr, IntPtr value); +#if EMBED + internal +#else + public +#endif + delegate int _put_PropertyAsString(IntPtr thisPtr, IntPtr value); [EditorBrowsable(EditorBrowsableState.Never)] #if EMBED internal diff --git a/src/WinRT.Runtime/Projections/IDictionary.net5.cs b/src/WinRT.Runtime/Projections/IDictionary.net5.cs index 7d9d29d7c..bb0c1faae 100644 --- a/src/WinRT.Runtime/Projections/IDictionary.net5.cs +++ b/src/WinRT.Runtime/Projections/IDictionary.net5.cs @@ -843,7 +843,12 @@ static FromAbiHelper _FromMap(IWinRTObject obj) { IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); } - public static class IDictionary_Delegates +#if EMBED + internal +#else + public +#endif + static class IDictionary_Delegates { public unsafe delegate int GetView_3(IntPtr thisPtr, out IntPtr __return_value__); public unsafe delegate int Clear_6(IntPtr thisPtr); diff --git a/src/WinRT.Runtime/Projections/IDisposable.net5.cs b/src/WinRT.Runtime/Projections/IDisposable.net5.cs index 774e82ebe..897942920 100644 --- a/src/WinRT.Runtime/Projections/IDisposable.net5.cs +++ b/src/WinRT.Runtime/Projections/IDisposable.net5.cs @@ -9,7 +9,12 @@ namespace ABI.System [DynamicInterfaceCastableImplementation] [EditorBrowsable(EditorBrowsableState.Never)] [Guid("30D5A829-7FA4-4026-83BB-D75BAE4EA99E")] - public unsafe interface IDisposable : global::System.IDisposable +#if EMBED + internal +#else + public +#endif + unsafe interface IDisposable : global::System.IDisposable { [Guid("30D5A829-7FA4-4026-83BB-D75BAE4EA99E")] public struct Vftbl diff --git a/src/WinRT.Runtime/Projections/IEnumerable.net5.cs b/src/WinRT.Runtime/Projections/IEnumerable.net5.cs index c3d2b52e3..1b292f060 100644 --- a/src/WinRT.Runtime/Projections/IEnumerable.net5.cs +++ b/src/WinRT.Runtime/Projections/IEnumerable.net5.cs @@ -182,8 +182,13 @@ private static FromAbiHelper _FromIterable(IWinRTObject _this) //System.Collections.Generic.IEnumerable`1.GetEnumerator() global::System.Collections.Generic.IEnumerator global::System.Collections.Generic.IEnumerable.GetEnumerator() => _FromIterable((IWinRTObject)this).GetEnumerator(); IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - } - public static class IEnumerable_Delegates + } +#if EMBED + internal +#else + public +#endif + static class IEnumerable_Delegates { public unsafe delegate int First_0(IntPtr thisPtr, out IntPtr __return_value__); } @@ -642,8 +647,14 @@ public unsafe bool HasCurrent public void Dispose() => _FromIterator.Dispose(); public T Current => _FromIterator.Current; object IEnumerator.Current => Current; - } - public static class IEnumerator_Delegates + } + +#if EMBED + internal +#else + public +#endif + static class IEnumerator_Delegates { public unsafe delegate int MoveNext_2(IntPtr thisPtr, out byte __return_value__); public unsafe delegate int GetMany_3(IntPtr thisPtr, int __itemsSize, IntPtr items, out uint __return_value__); diff --git a/src/WinRT.Runtime/Projections/IList.net5.cs b/src/WinRT.Runtime/Projections/IList.net5.cs index ceb734b52..9ba79c7fb 100644 --- a/src/WinRT.Runtime/Projections/IList.net5.cs +++ b/src/WinRT.Runtime/Projections/IList.net5.cs @@ -926,7 +926,13 @@ internal static FromAbiHelper _FromVector(IWinRTObject _this) global::System.Collections.Generic.IEnumerator global::System.Collections.Generic.IEnumerable.GetEnumerator() => _FromVector((IWinRTObject)this).GetEnumerator(); IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); } - public static class IList_Delegates + +#if EMBED + internal +#else + public +#endif + static class IList_Delegates { public unsafe delegate int GetView_2(IntPtr thisPtr, out IntPtr __return_value__); public unsafe delegate int RemoveAt_6(IntPtr thisPtr, uint index); diff --git a/src/WinRT.Runtime/Projections/IReadOnlyDictionary.net5.cs b/src/WinRT.Runtime/Projections/IReadOnlyDictionary.net5.cs index 6e66b414e..ecffd9958 100644 --- a/src/WinRT.Runtime/Projections/IReadOnlyDictionary.net5.cs +++ b/src/WinRT.Runtime/Projections/IReadOnlyDictionary.net5.cs @@ -721,7 +721,13 @@ private static FromAbiHelper _FromMapView(IWinRTObject _this) global::System.Collections.Generic.IEnumerator> global::System.Collections.Generic.IEnumerable>.GetEnumerator() => _FromMapView((IWinRTObject)this).GetEnumerator(); IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); } - public static class IReadOnlyDictionary_Delegates + +#if EMBED + internal +#else + public +#endif + static class IReadOnlyDictionary_Delegates { public unsafe delegate int Split_3(IntPtr thisPtr, out IntPtr first, out IntPtr second); } diff --git a/src/WinRT.Runtime/Projections/IReadOnlyList.net5.cs b/src/WinRT.Runtime/Projections/IReadOnlyList.net5.cs index 56ea37460..df12ddff3 100644 --- a/src/WinRT.Runtime/Projections/IReadOnlyList.net5.cs +++ b/src/WinRT.Runtime/Projections/IReadOnlyList.net5.cs @@ -434,7 +434,12 @@ internal static FromAbiHelper _FromVectorView(IWinRTObject _this) IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); } - public static class IReadOnlyList_Delegates +#if EMBED + internal +#else + public +#endif + static class IReadOnlyList_Delegates { public unsafe delegate int GetMany_3(IntPtr thisPtr, uint startIndex, int __itemsSize, IntPtr items, out uint __return_value__); } diff --git a/src/WinRT.Runtime/Projections/IReadOnlyList.netstandard2.0.cs b/src/WinRT.Runtime/Projections/IReadOnlyList.netstandard2.0.cs index 900c57b6b..e26aca2c5 100644 --- a/src/WinRT.Runtime/Projections/IReadOnlyList.netstandard2.0.cs +++ b/src/WinRT.Runtime/Projections/IReadOnlyList.netstandard2.0.cs @@ -15,9 +15,6 @@ namespace Windows.Foundation.Collections { [Guid("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56")] -#if EMBED - internal -#endif interface IVectorView : IIterable { T GetAt(uint index); @@ -443,6 +440,7 @@ public unsafe uint Size IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); } + #if EMBED internal #else diff --git a/src/WinRT.Runtime/Projections/Numerics.cs b/src/WinRT.Runtime/Projections/Numerics.cs index 3b6ac2671..7e43f3a0b 100644 --- a/src/WinRT.Runtime/Projections/Numerics.cs +++ b/src/WinRT.Runtime/Projections/Numerics.cs @@ -6,49 +6,84 @@ namespace ABI.System.Numerics { [StructLayout(LayoutKind.Sequential)] - public struct Matrix3x2 +#if EMBED + internal +#else + public +#endif + struct Matrix3x2 { public static string GetGuidSignature() => "struct(Windows.Foundation.Numerics.Matrix3x2;f4;f4;f4;f4;f4;f4)"; } [StructLayout(LayoutKind.Sequential)] - public struct Matrix4x4 +#if EMBED + internal +#else + public +#endif + struct Matrix4x4 { public static string GetGuidSignature() => "struct(Windows.Foundation.Numerics.Matrix4x4;f4;f4;f4;f4;f4;f4;f4;f4;f4;f4;f4;f4;f4;f4;f4;f4)"; } [StructLayout(LayoutKind.Sequential)] - public struct Plane +#if EMBED + internal +#else + public +#endif + struct Plane { public static string GetGuidSignature() => "struct(Windows.Foundation.Numerics.Plane;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);f4)"; } [StructLayout(LayoutKind.Sequential)] - public struct Quaternion +#if EMBED + internal +#else + public +#endif + struct Quaternion { public static string GetGuidSignature() => "struct(Windows.Foundation.Numerics.Quaternion;f4;f4;f4;f4)"; } [StructLayout(LayoutKind.Sequential)] - public struct Vector2 +#if EMBED + internal +#else + public +#endif + struct Vector2 { public static string GetGuidSignature() => "struct(Windows.Foundation.Numerics.Vector2;f4;f4)"; } [StructLayout(LayoutKind.Sequential)] - public struct Vector3 +#if EMBED + internal +#else + public +#endif + struct Vector3 { public static string GetGuidSignature() => "struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4)"; } [StructLayout(LayoutKind.Sequential)] - public struct Vector4 +#if EMBED + internal +#else + public +#endif + struct Vector4 { public static string GetGuidSignature() => "struct(Windows.Foundation.Numerics.Vector4;f4;f4;f4;f4)"; diff --git a/src/WinRT.Runtime/Projections/SystemTypes.cs b/src/WinRT.Runtime/Projections/SystemTypes.cs index 7330a3169..b918acd35 100644 --- a/src/WinRT.Runtime/Projections/SystemTypes.cs +++ b/src/WinRT.Runtime/Projections/SystemTypes.cs @@ -6,7 +6,12 @@ namespace ABI.System { [StructLayout(LayoutKind.Sequential)] - public struct TimeSpan +#if EMBED + internal +#else + public +#endif + struct TimeSpan { // NOTE: both 'Windows.Foundation.TimeSpan.Duration' and 'System.TimeSpan.Ticks' are in units of 100ns public long Duration; @@ -49,7 +54,12 @@ public static string GetGuidSignature() } [StructLayout(LayoutKind.Sequential)] - public struct DateTimeOffset +#if EMBED + internal +#else + public +#endif + struct DateTimeOffset { // NOTE: 'Windows.Foundation.DateTime.UniversalTime' is a FILETIME value (relative to 01/01/1601), however // 'System.DateTimeOffset.Ticks' is relative to 01/01/0001 @@ -105,7 +115,12 @@ public static string GetGuidSignature() } [StructLayout(LayoutKind.Sequential)] - public struct Exception +#if EMBED + internal +#else + public +#endif + struct Exception { public int hr; diff --git a/src/WinRT.Runtime/Projections/Type.cs b/src/WinRT.Runtime/Projections/Type.cs index b75db58c8..70ed12bbd 100644 --- a/src/WinRT.Runtime/Projections/Type.cs +++ b/src/WinRT.Runtime/Projections/Type.cs @@ -11,9 +11,14 @@ internal enum TypeKind : int Primitive, Metadata, Custom - } - - public struct Type + } + +#if EMBED + internal +#else + public +#endif + struct Type { private IntPtr Name; private TypeKind Kind; From b2b33ca02e8df6e0c896e2d25aba503a31472d4c Mon Sep 17 00:00:00 2001 From: Joshua Larkin <70237359+j0shuams@users.noreply.github.com> Date: Thu, 21 Oct 2021 21:51:04 -0700 Subject: [PATCH 08/11] conflict --- src/WinRT.Runtime/ComWrappersSupport.cs | 1 + src/WinRT.Runtime/ExceptionHelpers.cs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/WinRT.Runtime/ComWrappersSupport.cs b/src/WinRT.Runtime/ComWrappersSupport.cs index c561065d2..e180bd99f 100644 --- a/src/WinRT.Runtime/ComWrappersSupport.cs +++ b/src/WinRT.Runtime/ComWrappersSupport.cs @@ -7,6 +7,7 @@ using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using WinRT.Interop; #if NET diff --git a/src/WinRT.Runtime/ExceptionHelpers.cs b/src/WinRT.Runtime/ExceptionHelpers.cs index d6247ea6f..d321f3fe8 100644 --- a/src/WinRT.Runtime/ExceptionHelpers.cs +++ b/src/WinRT.Runtime/ExceptionHelpers.cs @@ -12,7 +12,7 @@ namespace WinRT #else public #endif - static class ExceptionHelpers + static unsafe class ExceptionHelpers { private const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622); private const int RO_E_CLOSED = unchecked((int)0x80000013); From ef7eac7f28228ade8a791553ad1e92506ab56b42 Mon Sep 17 00:00:00 2001 From: Joshua Larkin <70237359+j0shuams@users.noreply.github.com> Date: Fri, 22 Oct 2021 09:09:43 -0700 Subject: [PATCH 09/11] static class --- src/cswinrt/code_writers.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cswinrt/code_writers.h b/src/cswinrt/code_writers.h index 470e47b24..e295dad5b 100644 --- a/src/cswinrt/code_writers.h +++ b/src/cswinrt/code_writers.h @@ -5531,7 +5531,10 @@ public static Guid PIID = Vftbl.PIID; { % } -)", is_exclusive_to(iface) ? "internal" : "public", bind(iface, typedef_name_type::StaticAbiClass, false), bind(iface)); +)", + is_exclusive_to(iface) ? "internal" : internal_if_embedded(), + bind(iface, typedef_name_type::StaticAbiClass, false), + bind(iface)); } bool write_abi_interface(writer& w, TypeDef const& type) From 01ee662f33ebb104fe1deeb30c697e9477d6c748 Mon Sep 17 00:00:00 2001 From: Joshua Larkin <70237359+j0shuams@users.noreply.github.com> Date: Thu, 28 Oct 2021 08:55:00 -0700 Subject: [PATCH 10/11] + --- src/cswinrt/strings/WinRT.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/cswinrt/strings/WinRT.cs b/src/cswinrt/strings/WinRT.cs index a5f86dedd..3fdf1d854 100644 --- a/src/cswinrt/strings/WinRT.cs +++ b/src/cswinrt/strings/WinRT.cs @@ -114,7 +114,7 @@ public static bool TryLoad(string fileName, out DllModule module) return false; } } -+ + private static unsafe bool TryCreate(string fileName, out DllModule module) { // Explicitly look for module in the same directory as this one, and @@ -851,9 +851,7 @@ internal static class ProjectionInitializer #pragma warning restore 0436 internal static void InitalizeProjection() { -#if !EMBED ComWrappersSupport.RegisterProjectionAssembly(typeof(ProjectionInitializer).Assembly); -#endif } } } From 106f8a097a1474003c9b1e69ffab52940f85fa76 Mon Sep 17 00:00:00 2001 From: Joshua Larkin <70237359+j0shuams@users.noreply.github.com> Date: Thu, 28 Oct 2021 20:11:24 -0700 Subject: [PATCH 11/11] private --- .../additions/Windows.Foundation/Windows.Foundation.SR.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/cswinrt/strings/additions/Windows.Foundation/Windows.Foundation.SR.cs b/src/cswinrt/strings/additions/Windows.Foundation/Windows.Foundation.SR.cs index fd5b613bb..8126e3645 100644 --- a/src/cswinrt/strings/additions/Windows.Foundation/Windows.Foundation.SR.cs +++ b/src/cswinrt/strings/additions/Windows.Foundation/Windows.Foundation.SR.cs @@ -4,9 +4,6 @@ namespace Windows.Foundation { -#if EMBED - internal -#endif class SR { public static string Argument_BufferLengthExceedsCapacity = "The specified useful data length exceeds the capacity of this buffer.";