From 4be36205c4fd43cd5d33da03ac2f55ecd5c4c2eb Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Tue, 11 Aug 2020 15:27:46 -0700 Subject: [PATCH 01/23] Don't ship the netstandard2.0 projection support. --- nuget/Microsoft.Windows.CsWinRT.nuspec | 2 -- 1 file changed, 2 deletions(-) diff --git a/nuget/Microsoft.Windows.CsWinRT.nuspec b/nuget/Microsoft.Windows.CsWinRT.nuspec index e57ffa015..2665270be 100644 --- a/nuget/Microsoft.Windows.CsWinRT.nuspec +++ b/nuget/Microsoft.Windows.CsWinRT.nuspec @@ -14,7 +14,6 @@ LICENSE https://github.com/microsoft/cswinrt/tree/master/ - @@ -25,7 +24,6 @@ - From 7ad98c8b1ebcefb63432c08efa677c9514072f10 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Wed, 12 Aug 2020 14:16:21 -0700 Subject: [PATCH 02/23] Start refactoring for implementing IDynamicInterfaceCastable. --- cswinrt/code_writers.h | 74 ++++++++++++++++++++++++++++++++++++++---- cswinrt/main.cpp | 9 ++++- 2 files changed, 75 insertions(+), 8 deletions(-) diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index 7d794bd26..124fe47f4 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -841,8 +841,15 @@ set => %.% = value; std::string write_as_cast(writer& w, TypeDef const& iface, bool as_abi) { - return w.write_temp(as_abi ? "As<%>()" : "AsInternal(new InterfaceTag<%>())", - bind(iface, as_abi, false)); + if (settings.netstandard_compat) + { + return w.write_temp(as_abi ? "As<%>()" : "AsInternal(new InterfaceTag<%>())", + bind(iface, as_abi, false)); + } + else + { + return w.write_temp("((%)(IWinRTObject)this)", bind(iface, false, false)); + } } void write_lazy_interface_initialization(writer& w, TypeDef const& type) @@ -1664,7 +1671,6 @@ private % AsInternal(InterfaceTag<%> _) => ((Lazy<%>)_lazyInterfaces[typeof(%)]) void write_event_source_ctors(writer& w, TypeDef const& type) { - uint32_t const vtable_base = type.MethodList().first.index(); for (auto&& evt : type.EventList()) { auto [add, remove] = get_event_methods(evt); @@ -2676,7 +2682,15 @@ remove => _%.Unsubscribe(value); { if (!method.SpecialName()) { - auto method_target = w.write_temp("As<%>()", bind(iface, true, false)); + std::string_view method_target; + if (settings.netstandard_compat) + { + method_target = w.write_temp("As<%>()", bind(iface, true, false)); + } + else + { + method_target = w.write_temp("((%)(IWinRTObject)this)", bind(iface, false, false)); + } auto return_type = w.write_temp("%", bind(method_signature{ method })); write_explicitly_implemented_method(w, method, return_type, iface, method_target); } @@ -4054,7 +4068,7 @@ IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, ); } - bool write_abi_interface(writer& w, TypeDef const& type) + bool write_abi_interface_netstandard(writer& w, TypeDef const& type) { XLANG_ASSERT(get_category(type) == category::interface_type); auto type_name = write_type_name_temp(w, type, "%", true); @@ -4063,8 +4077,6 @@ IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, std::set generic_methods; std::vector nongeneric_delegates; - uint32_t const vtable_base = type.MethodList().first.index(); - std::map required_interfaces; write_required_interface_members_for_abi_type(w, type, required_interfaces); @@ -4162,6 +4174,54 @@ public static class % return true; } + bool write_abi_interface(writer& w, TypeDef const& type) + { + XLANG_ASSERT(get_category(type) == category::interface_type); + auto type_name = write_type_name_temp(w, type, "%", true); + auto is_generic = distance(type.GenericParam()) > 0; + std::set generic_methods; + std::vector nongeneric_delegates; + + std::map required_interfaces; + write_required_interface_members_for_abi_type(w, type, required_interfaces); + + w.write(R"([DynamicInterfaceCastableImplementation] +% +internal unsafe interface % : % +{ +%%%%%} +)", + // Interface abi implementation + bind(type), + type_name, + bind(type, false, false), + // Vftbl + bind(type, type_name, generic_methods, "", nongeneric_delegates), + [&](writer& w) { + for (auto required_interface : required_interfaces) + { + if (required_interface.second.helper_wrapper.empty()) + continue; + w.write("%.FromAbiHelper %;\n", + required_interface.second.helper_wrapper, + required_interface.second.adapter); + } + }, + bind(type, generic_methods), + bind(type), + [&](writer& w) { + for (auto required_interface : required_interfaces) + { + w.write("%", required_interface.second.members); + } + } + ); + + XLANG_ASSERT(nongeneric_delegates.empty()); + w.write("\n"); + + return true; + } void write_class(writer& w, TypeDef const& type) { diff --git a/cswinrt/main.cpp b/cswinrt/main.cpp index 937e6f7f1..e008b4a35 100644 --- a/cswinrt/main.cpp +++ b/cswinrt/main.cpp @@ -230,7 +230,14 @@ Where is one or more of: write_abi_delegate(w, type); break; case category::interface_type: - write_abi_interface(w, type); + if (settings.netstandard_compat) + { + write_abi_interface_netstandard(w, type); + } + else + { + write_abi_interface(w, type); + } break; case category::struct_type: if (!is_type_blittable(type)) From 58c590a5df88ceb508c787a9a1032096c20e4542 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Thu, 13 Aug 2020 13:33:32 -0700 Subject: [PATCH 03/23] Add IWinRTObject interface and continue implementing the updates to interfaces. --- WinRT.Runtime/IInspectable.cs | 2 +- WinRT.Runtime/IInspectable.net5.cs | 13 ++++++ WinRT.Runtime/IWinRTObject.net5.cs | 53 +++++++++++++++++++++++ WinRT.Runtime/ObjectReference.cs | 2 +- cswinrt/code_writers.h | 67 ++++++++++++++++++++---------- 5 files changed, 113 insertions(+), 24 deletions(-) create mode 100644 WinRT.Runtime/IInspectable.net5.cs create mode 100644 WinRT.Runtime/IWinRTObject.net5.cs diff --git a/WinRT.Runtime/IInspectable.cs b/WinRT.Runtime/IInspectable.cs index 7d21134c5..7b9791f09 100644 --- a/WinRT.Runtime/IInspectable.cs +++ b/WinRT.Runtime/IInspectable.cs @@ -16,7 +16,7 @@ public enum TrustLevel // IInspectable [ObjectReferenceWrapper(nameof(_obj))] [Guid("AF86E2E0-B12D-4c6a-9C5A-D7AA65101E90")] - public class IInspectable + public partial class IInspectable { [Guid("AF86E2E0-B12D-4c6a-9C5A-D7AA65101E90")] public unsafe struct Vftbl diff --git a/WinRT.Runtime/IInspectable.net5.cs b/WinRT.Runtime/IInspectable.net5.cs new file mode 100644 index 000000000..03b40c130 --- /dev/null +++ b/WinRT.Runtime/IInspectable.net5.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Concurrent; + +namespace WinRT +{ + public partial class IInspectable : IWinRTObject + { + IObjectReference IWinRTObject.NativeObject => _obj; + + ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new ConcurrentDictionary(); + } + +} diff --git a/WinRT.Runtime/IWinRTObject.net5.cs b/WinRT.Runtime/IWinRTObject.net5.cs new file mode 100644 index 000000000..fbd7df330 --- /dev/null +++ b/WinRT.Runtime/IWinRTObject.net5.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using WinRT.Interop; + +namespace WinRT +{ + public interface IWinRTObject : IDynamicInterfaceCastable + { + bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented) + { + Type type = Type.GetTypeFromHandle(interfaceType); + Type helperType = type.FindHelperType(); + if (helperType is null) + { + return false; + } + var vftblType = helperType.GetNestedType("Vftbl"); + int hr = NativeObject.TryAs(GuidGenerator.GetIID(helperType), out var objRef); + if (hr < 0) + { + if (throwIfNotImplemented) + { + ExceptionHelpers.ThrowExceptionForHR(hr); + } + return false; + } + using (objRef) + { + IObjectReference typedObjRef = (IObjectReference)typeof(IObjectReference).GetMethod("As", Type.EmptyTypes).MakeGenericMethod(vftblType).Invoke(objRef, null); + if (!QueryInterfaceCache.TryAdd(interfaceType, typedObjRef)) + { + typedObjRef.Dispose(); + } + return true; + } + } + + RuntimeTypeHandle IDynamicInterfaceCastable.GetInterfaceImplementation(RuntimeTypeHandle interfaceType) + { + return Type.GetTypeFromHandle(interfaceType).GetHelperType().TypeHandle; + } + + protected IObjectReference NativeObject { get; } + + protected ConcurrentDictionary QueryInterfaceCache { get; } + + IObjectReference GetObjectReferenceForType(RuntimeTypeHandle type) + { + return QueryInterfaceCache[type]; + } + } +} \ No newline at end of file diff --git a/WinRT.Runtime/ObjectReference.cs b/WinRT.Runtime/ObjectReference.cs index 295d0aaf6..c8ccc5ce7 100644 --- a/WinRT.Runtime/ObjectReference.cs +++ b/WinRT.Runtime/ObjectReference.cs @@ -56,7 +56,7 @@ public unsafe ObjectReference As(Guid iid) return ObjectReference.Attach(ref thatPtr); } - public int TryAs(out ObjectReference objRef) => TryAs(GuidGenerator.GetIID(typeof(T)), out objRef); + public int TryAs(out ObjectReference objRef) => TryAs(GuidGenerator.GetIID(typeof(T)), out objRef); public virtual unsafe int TryAs(Guid iid, out ObjectReference objRef) { diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index 124fe47f4..01a869aa6 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -2471,9 +2471,19 @@ internal static _% Instance => _instance.Value; { auto get_method_info = [&](MethodDef const& method) { + std::string obj_target; + if (settings.netstandard_compat) + { + obj_target = "_obj"; + } + else + { + obj_target = w.write_temp("((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(%))", + bind(type, false, false)); + } auto vmethod_name = get_vmethod_name(w, type, method); return std::pair{ - "_obj.Vftbl." + vmethod_name, + obj_target + ".Vftbl." + vmethod_name, generic_methods.find(vmethod_name) != generic_methods.end()}; }; @@ -2486,11 +2496,19 @@ internal static _% Instance => _instance.Value; method_signature signature{ method }; auto [invoke_target, is_generic] = get_method_info(method); w.write(R"( -public unsafe %% %(%) +%unsafe %% %%(%) {%} )", + settings.netstandard_compat ? "public " : "", (method.Name() == "ToString"sv) ? "override " : "", bind(signature), + bind([&](writer& w) + { + if (!settings.netstandard_compat) + { + w.write("%.", bind(type, false, false)); + } + }), method.Name(), bind_list(", ", signature.params()), bind(signature, invoke_target, is_generic, false)); @@ -2500,10 +2518,18 @@ public unsafe %% %(%) { auto [getter, setter] = get_property_methods(prop); w.write(R"( -public unsafe % % +%unsafe % %% { )", + settings.netstandard_compat ? "public " : "", write_prop_type(w, prop), + bind([&](writer& w) + { + if (!settings.netstandard_compat) + { + w.write("%.", bind(type, false, false)); + } + }), prop.Name()); if (getter) { @@ -2520,7 +2546,8 @@ public unsafe % % if (!getter) { auto getter_interface = find_property_interface(w, type, prop.Name()); - w.write("get{ return As<%>().%; }\n", getter_interface.first, prop.Name()); + auto getter_cast = settings.netstandard_compat ? "As<%>()"s : "((%)(IWinRTObject)this)"s; + w.write("get{ return " + getter_cast + "().%; }\n", getter_interface.first, prop.Name()); } auto [invoke_target, is_generic] = get_method_info(setter); auto signature = method_signature(setter); @@ -2538,13 +2565,20 @@ public unsafe % % { auto semantics = get_type_semantics(evt.EventType()); w.write(R"( -public event % % +public event % %% { add => _%.Subscribe(value); remove => _%.Unsubscribe(value); } )", bind(get_type_semantics(evt.EventType()), false, false), + bind([&](writer& w) + { + if (!settings.netstandard_compat) + { + w.write("%.", bind(type, false, false)); + } + }), evt.Name(), evt.Name(), evt.Name()); @@ -2559,7 +2593,7 @@ remove => _%.Unsubscribe(value); }; void write_required_interface_members_for_abi_type(writer& w, TypeDef const& type, - std::map& required_interfaces) + std::map& required_interfaces, bool emit_mapped_type_helpers) { auto write_required_interface = [&](TypeDef const& iface) { @@ -2570,7 +2604,7 @@ remove => _%.Unsubscribe(value); return; } - if (auto mapping = get_mapped_type(iface.TypeNamespace(), iface.TypeName())) + if (auto mapping = get_mapped_type(iface.TypeNamespace(), iface.TypeName()); mapping && emit_mapped_type_helpers) { auto remove_enumerable = [&](std::string generic_enumerable = "") { @@ -2708,7 +2742,7 @@ remove => _%.Unsubscribe(value); if (has_attribute(iface, "Windows.Foundation.Metadata", "OverridableAttribute") || !is_exclusive_to(type)) { write_required_interface(type); - write_required_interface_members_for_abi_type(w, type, required_interfaces); + write_required_interface_members_for_abi_type(w, type, required_interfaces, emit_mapped_type_helpers); } }); } @@ -4078,7 +4112,7 @@ IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, std::vector nongeneric_delegates; std::map required_interfaces; - write_required_interface_members_for_abi_type(w, type, required_interfaces); + write_required_interface_members_for_abi_type(w, type, required_interfaces, true); w.write(R"([global::WinRT.ObjectReferenceWrapper(nameof(_obj))] % @@ -4178,18 +4212,17 @@ public static class % { XLANG_ASSERT(get_category(type) == category::interface_type); auto type_name = write_type_name_temp(w, type, "%", true); - auto is_generic = distance(type.GenericParam()) > 0; std::set generic_methods; std::vector nongeneric_delegates; std::map required_interfaces; - write_required_interface_members_for_abi_type(w, type, required_interfaces); + write_required_interface_members_for_abi_type(w, type, required_interfaces, false); w.write(R"([DynamicInterfaceCastableImplementation] % internal unsafe interface % : % { -%%%%%} +%%%%} )", // Interface abi implementation bind(type), @@ -4197,16 +4230,6 @@ internal unsafe interface % : % bind(type, false, false), // Vftbl bind(type, type_name, generic_methods, "", nongeneric_delegates), - [&](writer& w) { - for (auto required_interface : required_interfaces) - { - if (required_interface.second.helper_wrapper.empty()) - continue; - w.write("%.FromAbiHelper %;\n", - required_interface.second.helper_wrapper, - required_interface.second.adapter); - } - }, bind(type, generic_methods), bind(type), [&](writer& w) { From 6e455f3044189ef127e4529368162b050a23f792 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Thu, 13 Aug 2020 15:49:02 -0700 Subject: [PATCH 04/23] Implement IDynamicInterfaceCastable for generated code excluding factories and FromAbi. --- cswinrt/code_writers.h | 381 +++++++++++++++++++++++++++++------------ cswinrt/main.cpp | 9 +- 2 files changed, 281 insertions(+), 109 deletions(-) diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index 01a869aa6..a0de5e8d0 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -1565,13 +1565,25 @@ target); auto target = is_default_interface ? "_default" : write_type_name_temp(w, interface_type, "AsInternal(new InterfaceTag<%>())"); if (!is_default_interface) { - w.write(R"( + if (settings.netstandard_compat) + { + w.write(R"( private % AsInternal(InterfaceTag<%> _) => ((Lazy<%>)_lazyInterfaces[typeof(%)]).Value; )", - interface_name, - interface_name, - interface_abi_name, - interface_name); + interface_name, + interface_name, + interface_abi_name, + interface_name); + } + else + { + w.write(R"( +private % AsInternal(InterfaceTag<%> _) => (%)(object)this; +)", + interface_name, + interface_name, + interface_name); + } } if(auto mapping = get_mapped_type(interface_type.TypeNamespace(), interface_type.TypeName()); mapping && mapping->has_custom_members_output) @@ -1669,22 +1681,16 @@ private % AsInternal(InterfaceTag<%> _) => ((Lazy<%>)_lazyInterfaces[typeof(%)]) ); } - void write_event_source_ctors(writer& w, TypeDef const& type) + void write_event_source_ctor(writer& w, Event const& evt) { - for (auto&& evt : type.EventList()) - { - auto [add, remove] = get_event_methods(evt); - w.write(R"( - -_% = + auto [add, remove] = get_event_methods(evt); + w.write(R"( new EventSource<%>(_obj, _obj.Vftbl.%, - _obj.Vftbl.%);)", - evt.Name(), - bind(get_type_semantics(evt.EventType()), false, false), - get_vmethod_name(w, type, add), - get_vmethod_name(w, type, remove)); - } + _obj.Vftbl.%))", + bind(get_type_semantics(evt.EventType()), false, false), + get_vmethod_name(w, evt.Parent(), add), + get_vmethod_name(w, evt.Parent(), remove)); } void write_event_sources(writer& w, TypeDef const& type) @@ -1693,8 +1699,19 @@ _% = { w.write(R"( private EventSource<%> _%;)", - bind(get_type_semantics(evt.EventType()), false, false), - evt.Name()); +bind(get_type_semantics(evt.EventType()), false, false), +evt.Name()); + } + } + + void write_event_source_tables(writer& w, TypeDef const& type) + { + for (auto&& evt : type.EventList()) + { + w.write(R"( +private static global::System.Runtime.CompilerServices.ConditionalWeakTable> _% = new();)", +bind(get_type_semantics(evt.EventType()), false, false), +evt.Name()); } } @@ -2471,22 +2488,22 @@ internal static _% Instance => _instance.Value; { auto get_method_info = [&](MethodDef const& method) { - std::string obj_target; - if (settings.netstandard_compat) - { - obj_target = "_obj"; - } - else - { - obj_target = w.write_temp("((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(%))", - bind(type, false, false)); - } auto vmethod_name = get_vmethod_name(w, type, method); return std::pair{ - obj_target + ".Vftbl." + vmethod_name, + "_obj.Vftbl." + vmethod_name, generic_methods.find(vmethod_name) != generic_methods.end()}; }; + auto init_call_variables = [&](writer& w) + { + if (!settings.netstandard_compat) + { + w.write("\nvar _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(%).TypeHandle));\n", + bind(type, false, false)); + w.write("var ThisPtr = _obj.ThisPtr;\n"); + } + }; + for (auto&& method : type.MethodList()) { if (is_special(method)) @@ -2497,7 +2514,7 @@ internal static _% Instance => _instance.Value; auto [invoke_target, is_generic] = get_method_info(method); w.write(R"( %unsafe %% %%(%) -{%} +{%%} )", settings.netstandard_compat ? "public " : "", (method.Name() == "ToString"sv) ? "override " : "", @@ -2511,6 +2528,7 @@ internal static _% Instance => _instance.Value; }), method.Name(), bind_list(", ", signature.params()), + bind(init_call_variables), bind(signature, invoke_target, is_generic, false)); } @@ -2537,8 +2555,9 @@ internal static _% Instance => _instance.Value; auto signature = method_signature(getter); auto marshalers = get_abi_marshalers(w, signature, is_generic, prop.Name()); w.write(R"(get -{%} +{%%} )", + bind(init_call_variables), bind(invoke_target, is_generic, marshalers)); } if (setter) @@ -2547,15 +2566,16 @@ internal static _% Instance => _instance.Value; { auto getter_interface = find_property_interface(w, type, prop.Name()); auto getter_cast = settings.netstandard_compat ? "As<%>()"s : "((%)(IWinRTObject)this)"s; - w.write("get{ return " + getter_cast + "().%; }\n", getter_interface.first, prop.Name()); + w.write("get{ return " + getter_cast + ".%; }\n", getter_interface.first, prop.Name()); } auto [invoke_target, is_generic] = get_method_info(setter); auto signature = method_signature(setter); auto marshalers = get_abi_marshalers(w, signature, is_generic, prop.Name()); marshalers[0].param_name = "value"; w.write(R"(set -{%} +{%%} )", + bind(init_call_variables), bind(invoke_target, is_generic, marshalers)); } w.write("}\n"); @@ -2564,13 +2584,17 @@ internal static _% Instance => _instance.Value; for (auto&& evt : type.EventList()) { auto semantics = get_type_semantics(evt.EventType()); + auto event_source = settings.netstandard_compat ? + w.write_temp("_%", evt.Name()) + : w.write_temp("_%.GetValue((IWinRTObject)this, (key) => { var _obj = (ObjectReference)key.GetObjectReferenceForType(typeof(%).TypeHandle); return %; })", evt.Name(), bind(type, false, false), bind(evt)); w.write(R"( -public event % %% +%event % %% { -add => _%.Subscribe(value); -remove => _%.Unsubscribe(value); +add => %.Subscribe(value); +remove => %.Unsubscribe(value); } )", + settings.netstandard_compat ? "public " : "", bind(get_type_semantics(evt.EventType()), false, false), bind([&](writer& w) { @@ -2580,8 +2604,8 @@ remove => _%.Unsubscribe(value); } }), evt.Name(), - evt.Name(), - evt.Name()); + event_source, + event_source); } } @@ -2716,7 +2740,7 @@ remove => _%.Unsubscribe(value); { if (!method.SpecialName()) { - std::string_view method_target; + std::string method_target; if (settings.netstandard_compat) { method_target = w.write_temp("As<%>()", bind(iface, true, false)); @@ -3843,7 +3867,7 @@ IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, ); } - void write_base_constructor_dispatch(writer& w, type_semantics type) + void write_base_constructor_dispatch_netstandard(writer& w, type_semantics type) { std::string base_default_interface_name; call(type, @@ -3857,7 +3881,7 @@ IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, auto guard{ w.push_generic_args(inst) }; base_default_interface_name = get_default_interface_name(w, inst.generic_type); }, - [](auto) + [](auto) { throw_invalid("Invalid base class type."); }); @@ -3871,6 +3895,33 @@ IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, } } + void write_base_constructor_dispatch(writer& w, type_semantics type) + { + std::string base_default_interface_name; + call(type, + [&](object_type) {}, + [&](type_definition const& def) + { + base_default_interface_name = get_default_interface_name(w, def); + }, + [&](generic_type_instance const& inst) + { + auto guard{ w.push_generic_args(inst) }; + base_default_interface_name = get_default_interface_name(w, inst.generic_type); + }, + [](auto) + { + throw_invalid("Invalid base class type."); + }); + + if (!std::holds_alternative(type)) + { + w.write(R"( + : base(objRef) +)"); + } + } + void write_custom_attributes(writer& w, TypeDef const& type) { auto write_fixed_arg = [&](writer& w, FixedArgSig arg) @@ -4162,7 +4213,11 @@ public static Guid PIID = Vftbl.PIID; type_name, type.TypeName(), type.TypeName(), - bind(type), + bind_each([&](writer& w, Event const& evt) + { + w.write("_% = %;\n", evt.Name(), bind(evt)); + }, + type.EventList()), [&](writer& w) { for (auto required_interface : required_interfaces) { @@ -4231,7 +4286,7 @@ internal unsafe interface % : % // Vftbl bind(type, type_name, generic_methods, "", nongeneric_delegates), bind(type, generic_methods), - bind(type), + bind(type), [&](writer& w) { for (auto required_interface : required_interfaces) { @@ -4246,7 +4301,73 @@ internal unsafe interface % : % return true; } - void write_class(writer& w, TypeDef const& type) + void write_custom_query_interface_impl(writer& w, TypeDef const& type) + { + + bool has_base_class = !std::holds_alternative(get_type_semantics(type.Extends())); + separator s{ w, " || " }; + w.write(R"( +%bool IsOverridableInterface(Guid iid) => %%; + +global::System.Runtime.InteropServices.CustomQueryInterfaceResult global::System.Runtime.InteropServices.ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) +{ +ppv = IntPtr.Zero; +if (IsOverridableInterface(iid) || typeof(global::WinRT.IInspectable).GUID == iid) +{ +return global::System.Runtime.InteropServices.CustomQueryInterfaceResult.NotHandled; +} + +if (GetReferenceForQI().TryAs(iid, out ObjectReference objRef) >= 0) +{ +using (objRef) +{ +ppv = objRef.GetRef(); +return global::System.Runtime.InteropServices.CustomQueryInterfaceResult.Handled; +} +} + +return global::System.Runtime.InteropServices.CustomQueryInterfaceResult.NotHandled; +})", + bind([&](writer& w) + { + auto visibility = "protected "; + auto overridable = "virtual "; + if (has_base_class) + { + overridable = "override "; + } + else if (type.Flags().Sealed()) + { + visibility = "private "; + overridable = ""; + } + w.write(visibility); + w.write(overridable); + }), + bind_each([&](writer& w, InterfaceImpl const& iface) + { + if (has_attribute(iface, "Windows.Foundation.Metadata", "OverridableAttribute")) + { + s(); + w.write("GuidGenerator.GetIID(typeof(%)) == iid", + bind(get_type_semantics(iface.Interface()), false, false)); + } + }, type.InterfaceImpl()), + bind([&](writer& w) + { + if (has_base_class) + { + s(); + w.write("base.IsOverridableInterface(iid)"); + } + if (s.first) + { + w.write("false"); + } + })); + } + + void write_class_netstandard(writer& w, TypeDef const& type) { if (is_static(type)) { @@ -4318,7 +4439,7 @@ private % AsInternal(InterfaceTag<%> _) => _default; type.Flags().Sealed() ? "internal" : "protected internal", type_name, default_interface_abi_name, - bind(base_semantics), + bind(base_semantics), default_interface_abi_name, bind(type), type_name, @@ -4340,14 +4461,13 @@ _lazyInterfaces = new Dictionary() {% }; })", -type.TypeName(), -has_base_type ? ":base(_)" : "", -default_interface_abi_name, -default_interface_abi_name, -bind(type)); + type.TypeName(), + has_base_type ? ":base(_)" : "", + default_interface_abi_name, + default_interface_abi_name, + bind(type)); } - std::string_view access_spec = "protected "; std::string_view override_spec = has_base_type ? "override " : "virtual "; @@ -4370,70 +4490,115 @@ bind(type)); default_interface_name, default_interface_name, bind(type), - bind([&](writer& w) - { - bool has_base_class = !std::holds_alternative(get_type_semantics(type.Extends())); - separator s{ w, " || " }; - w.write(R"( -%bool IsOverridableInterface(Guid iid) => %%; + bind(type)); + } -global::System.Runtime.InteropServices.CustomQueryInterfaceResult global::System.Runtime.InteropServices.ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) + void write_class(writer& w, TypeDef const& type) + { + if (is_static(type)) + { + write_static_class(w, type); + return; + } + + auto type_name = write_type_name_temp(w, type); + auto default_interface_name = get_default_interface_name(w, type, false); + auto default_interface_abi_name = get_default_interface_name(w, type, true); + auto base_semantics = get_type_semantics(type.Extends()); + auto derived_new = std::holds_alternative(base_semantics) ? "" : "new "; + + w.write(R"([global::WinRT.WindowsRuntimeType] +[global::WinRT.ObjectReferenceWrapper(nameof(_inner))] +%public %class %%, IWinRTObject, IEquatable<%> { -ppv = IntPtr.Zero; -if (IsOverridableInterface(iid) || typeof(global::WinRT.IInspectable).GUID == iid) +public %IntPtr ThisPtr => _inner.ThisPtr; + +private IObjectReference _inner = null; +private readonly Lazy<%> _defaultLazy; + +private % _default => _defaultLazy.Value; +% +public static %% FromAbi(IntPtr thisPtr) { -return global::System.Runtime.InteropServices.CustomQueryInterfaceResult.NotHandled; +if (thisPtr == IntPtr.Zero) return null; +var obj = MarshalInspectable.FromAbi(thisPtr); +return obj is % ? (%)obj : new %((%)obj); } -if (GetReferenceForQI().TryAs(iid, out ObjectReference objRef) >= 0) -{ -using (objRef) +% %(IObjectReference objRef)% { -ppv = objRef.GetRef(); -return global::System.Runtime.InteropServices.CustomQueryInterfaceResult.Handled; -} +_inner = objRef; +_defaultLazy = new Lazy<%>(() => (%)(object)this); } -return global::System.Runtime.InteropServices.CustomQueryInterfaceResult.NotHandled; -})", - bind([&](writer& w) - { - auto visibility = "protected "; - auto overridable = "virtual "; - if (has_base_class) - { - overridable = "override "; - } - else if (type.Flags().Sealed()) - { - visibility = "private "; - overridable = ""; - } - w.write(visibility); - w.write(overridable); - }), - bind_each([&](writer& w, InterfaceImpl const& iface) - { - if (has_attribute(iface, "Windows.Foundation.Metadata", "OverridableAttribute")) - { - s(); - w.write("GuidGenerator.GetIID(typeof(%)) == iid", - bind(get_type_semantics(iface.Interface()), false, false)); - } - }, type.InterfaceImpl()), - bind([&](writer& w) +public static bool operator ==(% x, % y) => (x?.ThisPtr ?? IntPtr.Zero) == (y?.ThisPtr ?? IntPtr.Zero); +public static bool operator !=(% x, % y) => !(x == y); +public bool Equals(% other) => this == other; +public override bool Equals(object obj) => obj is % that && this == that; +public override int GetHashCode() => ThisPtr.GetHashCode(); +% + +private struct InterfaceTag{}; + +private % AsInternal(InterfaceTag<%> _) => _default; +%% +} +)", + bind(type), + bind(type), + type_name, + bind(type, base_semantics, true), + type_name, + derived_new, + default_interface_name, + default_interface_name, + bind(type), + derived_new, + type_name, + type_name, + type_name, + type_name, + default_interface_abi_name, + // ObjectReference constructor + type.Flags().Sealed() ? "internal" : "protected internal", + type_name, + bind(base_semantics), + default_interface_name, + default_interface_name, + // Equality operators + type_name, + type_name, + type_name, + type_name, + type_name, + type_name, + bind([&](writer& w) + { + bool has_base_type = !std::holds_alternative(get_type_semantics(type.Extends())); + if (!type.Flags().Sealed()) { - if (has_base_class) - { - s(); - w.write("base.IsOverridableInterface(iid)"); - } - if (s.first) - { - w.write("false"); - } - })); - })); + w.write(R"( +protected %(global::WinRT.DerivedComposed _)% +{ +_defaultLazy = new Lazy<%>(() => (%)(object)this); +})", +type.TypeName(), +has_base_type ? ":base(_)" : "", +default_interface_name, +default_interface_name); + } + + w.write(R"( +private IObjectReference GetReferenceForQI() => _inner; + +IObjectReference IWinRTObject.NativeObject => GetReferenceForQI(); + +global::System.Collections.Concurrent.ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new();)"); + }), + default_interface_name, + default_interface_name, + bind(type), + bind(type)); } void write_abi_class(writer& w, TypeDef const& type) diff --git a/cswinrt/main.cpp b/cswinrt/main.cpp index e008b4a35..64014f2b7 100644 --- a/cswinrt/main.cpp +++ b/cswinrt/main.cpp @@ -178,7 +178,14 @@ Where is one or more of: } else { - write_class(w, type); + if (settings.netstandard_compat) + { + write_class_netstandard(w, type); + } + else + { + write_class(w, type); + } } break; case category::delegate_type: From 686cead239f87ee0aac0a16330beb8e5f7ad253a Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Thu, 13 Aug 2020 16:23:06 -0700 Subject: [PATCH 05/23] Add fallback for when an interface is kept alive but its Vftbl type was linked away since no members on the interface were called. --- WinRT.Runtime/IWinRTObject.net5.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/WinRT.Runtime/IWinRTObject.net5.cs b/WinRT.Runtime/IWinRTObject.net5.cs index fbd7df330..458679a3e 100644 --- a/WinRT.Runtime/IWinRTObject.net5.cs +++ b/WinRT.Runtime/IWinRTObject.net5.cs @@ -15,7 +15,6 @@ bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfac { return false; } - var vftblType = helperType.GetNestedType("Vftbl"); int hr = NativeObject.TryAs(GuidGenerator.GetIID(helperType), out var objRef); if (hr < 0) { @@ -25,6 +24,20 @@ bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfac } return false; } + var vftblType = helperType.GetNestedType("Vftbl"); + if (vftblType is null) + { + // The helper type might not have a vftbl type if it was linked away. + // The only time the Vftbl type would be linked away is when we don't actually use + // any of the methods on the interface (it was just a type cast/"is Type" check). + // In that case, we can use the IUnknownVftbl-typed ObjectReference since + // it has all of the information we'll need. + if (!QueryInterfaceCache.TryAdd(interfaceType, objRef)) + { + objRef.Dispose(); + } + return true; + } using (objRef) { IObjectReference typedObjRef = (IObjectReference)typeof(IObjectReference).GetMethod("As", Type.EmptyTypes).MakeGenericMethod(vftblType).Invoke(objRef, null); From 4fd093b86c827ca5507cea942d96a1bd3c155ca0 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Thu, 13 Aug 2020 17:17:24 -0700 Subject: [PATCH 06/23] Move statics and factory caches to the IDynamicInterfaceCastable plan. --- WinRT.Runtime/IInspectable.net5.cs | 2 +- cswinrt/code_writers.h | 156 +++++++++++++++++++---------- 2 files changed, 106 insertions(+), 52 deletions(-) diff --git a/WinRT.Runtime/IInspectable.net5.cs b/WinRT.Runtime/IInspectable.net5.cs index 03b40c130..4ccd8bef1 100644 --- a/WinRT.Runtime/IInspectable.net5.cs +++ b/WinRT.Runtime/IInspectable.net5.cs @@ -7,7 +7,7 @@ public partial class IInspectable : IWinRTObject { IObjectReference IWinRTObject.NativeObject => _obj; - ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new ConcurrentDictionary(); + ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); } } diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index a0de5e8d0..86c4e64e5 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -1039,16 +1039,19 @@ remove => %.% -= value; std::string write_static_cache_object(writer& w, std::string_view cache_type_name, TypeDef const& class_type) { + auto cache_vftbl_type = w.write_temp("ABI.%.%.Vftbl", + class_type.TypeNamespace(), + cache_type_name); auto cache_interface = w.write_temp( - R"((new BaseActivationFactory("%", "%.%"))._As)", + R"((new BaseActivationFactory("%", "%.%"))._As<%>)", class_type.TypeNamespace(), class_type.TypeNamespace(), class_type.TypeName(), - class_type.TypeNamespace(), - cache_type_name); - - w.write(R"( + cache_vftbl_type); + if (settings.netstandard_compat) + { + w.write(R"( internal class _% : ABI.%.% { public _%() : base(%()) { } @@ -1056,14 +1059,42 @@ private static WeakLazy<_%> _instance = new WeakLazy<_%>(); internal static % Instance => _instance.Value; } )", - cache_type_name, - class_type.TypeNamespace(), - cache_type_name, - cache_type_name, - cache_interface, - cache_type_name, - cache_type_name, - cache_type_name); + cache_type_name, + class_type.TypeNamespace(), + cache_type_name, + cache_type_name, + cache_interface, + cache_type_name, + cache_type_name, + cache_type_name); + } + else + { + w.write(R"( +internal class _% : IWinRTObject +{ +private ObjectReference<%> _obj; +public _%() +{ +_obj = %(); +} + +private static WeakLazy<_%> _instance = new WeakLazy<_%>(); +internal static % Instance => (%)_instance.Value; + +IObjectReference IWinRTObject.NativeObject => _obj; +global::System.Collections.Concurrent.ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); +} +)", + cache_type_name, + cache_vftbl_type, + cache_type_name, + cache_interface, + cache_type_name, + cache_type_name, + cache_type_name, + cache_type_name); + } return w.write_temp("_%.Instance", cache_type_name); } @@ -2331,7 +2362,8 @@ finally } void write_abi_method_with_raw_return_type(writer& w, MethodDef const& method) - { if (is_special(method)) + { + if (is_special(method)) { return; } @@ -2361,9 +2393,11 @@ finally method_signature signature{ method }; auto [invoke_target, is_generic] = get_method_info(method); w.write(R"( -public unsafe new % %(%) +public unsafe %% %(%) {%} )", + // In the .NET Standard 2.0 code-gen, the fully-projected signature will be available in the base class, so we need to specify new to hide it + settings.netstandard_compat ? "new " : "", bind(write_raw_return_type, signature), method.Name(), bind_list(", ", signature.params()), @@ -2452,15 +2486,16 @@ public unsafe % %(%) std::string write_factory_cache_object(writer& w, TypeDef const& factory_type, TypeDef const& class_type) { std::string_view cache_type_name = factory_type.TypeName(); - + auto cache_vftbl_type = w.write_temp("ABI.%.%.Vftbl", class_type.TypeNamespace(), cache_type_name); auto cache_interface = w.write_temp( - R"(ActivationFactory<%>.As)", + R"(ActivationFactory<%>.As<%>)", class_type.TypeName(), - class_type.TypeNamespace(), - cache_type_name); + cache_vftbl_type); + if (settings.netstandard_compat) + { - w.write(R"( + w.write(R"( internal class _% : ABI.%.% { public _%() : base(%()) { } @@ -2469,16 +2504,47 @@ internal static _% Instance => _instance.Value; % } )", - cache_type_name, - class_type.TypeNamespace(), - cache_type_name, - cache_type_name, - cache_interface, - cache_type_name, - cache_type_name, - cache_type_name, - bind_each(factory_type.MethodList()) - ); + cache_type_name, + class_type.TypeNamespace(), + cache_type_name, + cache_type_name, + cache_interface, + cache_type_name, + cache_type_name, + cache_type_name, + bind_each(factory_type.MethodList()) + ); + } + else + { + w.write(R"( +internal class _% : IWinRTObject +{ +private ObjectReference<%> _obj; +private IntPtr ThisPtr => _obj.ThisPtr; +public _%() +{ +_obj = %(); +} + +private static WeakLazy<_%> _instance = new WeakLazy<_%>(); +internal static _% Instance => _instance.Value; + +IObjectReference IWinRTObject.NativeObject => _obj; +global::System.Collections.Concurrent.ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); + +% +} +)", + cache_type_name, + cache_vftbl_type, + cache_type_name, + cache_interface, + cache_type_name, + cache_type_name, + cache_type_name, + bind_each(factory_type.MethodList())); + } return w.write_temp("_%.Instance", cache_type_name); } @@ -3897,23 +3963,6 @@ IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, void write_base_constructor_dispatch(writer& w, type_semantics type) { - std::string base_default_interface_name; - call(type, - [&](object_type) {}, - [&](type_definition const& def) - { - base_default_interface_name = get_default_interface_name(w, def); - }, - [&](generic_type_instance const& inst) - { - auto guard{ w.push_generic_args(inst) }; - base_default_interface_name = get_default_interface_name(w, inst.generic_type); - }, - [](auto) - { - throw_invalid("Invalid base class type."); - }); - if (!std::holds_alternative(type)) { w.write(R"( @@ -4522,12 +4571,17 @@ public static %% FromAbi(IntPtr thisPtr) { if (thisPtr == IntPtr.Zero) return null; var obj = MarshalInspectable.FromAbi(thisPtr); -return obj is % ? (%)obj : new %((%)obj); +if (obj is % result) +{ +return result; +} +using IObjectReference objRef = MarshalInspectable.CreateMarshaler(obj); +return new %(objRef); } % %(IObjectReference objRef)% { -_inner = objRef; +_inner = objRef.As<%.Vftbl>(); _defaultLazy = new Lazy<%>(() => (%)(object)this); } @@ -4553,16 +4607,16 @@ private % AsInternal(InterfaceTag<%> _) => _default; default_interface_name, default_interface_name, bind(type), + // FromAbi derived_new, type_name, type_name, type_name, - type_name, - default_interface_abi_name, // ObjectReference constructor type.Flags().Sealed() ? "internal" : "protected internal", type_name, bind(base_semantics), + default_interface_abi_name, default_interface_name, default_interface_name, // Equality operators From 89a83eede7b937d56da90f1b11fd858802bdcd46 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Thu, 13 Aug 2020 17:20:38 -0700 Subject: [PATCH 07/23] Use the QI cache when checking if an interface is implemented. --- WinRT.Runtime/IWinRTObject.net5.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/WinRT.Runtime/IWinRTObject.net5.cs b/WinRT.Runtime/IWinRTObject.net5.cs index 458679a3e..ae9686a80 100644 --- a/WinRT.Runtime/IWinRTObject.net5.cs +++ b/WinRT.Runtime/IWinRTObject.net5.cs @@ -9,6 +9,10 @@ public interface IWinRTObject : IDynamicInterfaceCastable { bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented) { + if (QueryInterfaceCache.TryGetValue(interfaceType, out _)) + { + return true; + } Type type = Type.GetTypeFromHandle(interfaceType); Type helperType = type.FindHelperType(); if (helperType is null) From 6511ae6c6c640c8ae99e634b2810802dea4fa9ac Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Thu, 13 Aug 2020 17:37:15 -0700 Subject: [PATCH 08/23] Move activation/composition to work with IDynamicInterfaceCastable. --- cswinrt/code_writers.h | 78 ++++++++++++++++++++++++++++++------------ 1 file changed, 57 insertions(+), 21 deletions(-) diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index 86c4e64e5..cab707224 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -1119,7 +1119,7 @@ public %(%) : this(((Func<%>)(() => { IntPtr ptr = (%.%(%)); try { -return new %(ComWrappersSupport.GetObjectReferenceForInterface(ptr)); +return %(ComWrappersSupport.GetObjectReferenceForInterface(ptr)); } finally { @@ -1132,23 +1132,23 @@ MarshalInspectable.DisposeAbi(ptr); )", class_type.TypeName(), bind_list(", ", signature.params()), - default_interface_name, + settings.netstandard_compat ? default_interface_name : "IObjectReference", cache_object, method.Name(), bind_list(", ", signature.params()), - default_interface_name); + settings.netstandard_compat ? "new " + default_interface_name : ""); } } else { w.write(R"( -public %() : this(new %(ActivationFactory<%>.ActivateInstance<%.Vftbl>())) +public %() : this(%(ActivationFactory<%>.ActivateInstance<%.Vftbl>())) { ComWrappersSupport.RegisterObjectForInterface(this, ThisPtr); } )", class_type.TypeName(), - default_interface_name, + settings.netstandard_compat ? "new " + default_interface_name : "", class_type.TypeName(), default_interface_name); } @@ -1157,7 +1157,8 @@ ComWrappersSupport.RegisterObjectForInterface(this, ThisPtr); void write_composable_constructors(writer& w, TypeDef const& composable_type, TypeDef const& class_type, std::string_view visibility) { auto cache_object = write_factory_cache_object(w, composable_type, class_type); - auto default_interface_name = get_default_interface_name(w, class_type); + auto default_interface_name = get_default_interface_name(w, class_type, false); + auto default_interface_abi_name = get_default_interface_name(w, class_type); for (auto&& method : composable_type.MethodList()) { @@ -1167,7 +1168,9 @@ ComWrappersSupport.RegisterObjectForInterface(this, ThisPtr); params_without_objects.pop_back(); params_without_objects.pop_back(); - w.write(R"( + if (settings.netstandard_compat) + { + w.write(R"( % %(%)% { object baseInspectable = this.GetType() != typeof(%) ? this : null; @@ -1190,18 +1193,52 @@ MarshalInspectable.DisposeAbi(ptr); } } )", - visibility, - class_type.TypeName(), - bind_list(", ", params_without_objects), - has_base_type ? ":base(global::WinRT.DerivedComposed.Instance)" : "", - bind(class_type, false, false), - cache_object, - method.Name(), - bind_list(", ", params_without_objects), - [&](writer& w) {w.write("%", params_without_objects.empty() ? " " : ", "); }, - default_interface_name, - default_interface_name, - bind(class_type)); + visibility, + class_type.TypeName(), + bind_list(", ", params_without_objects), + has_base_type ? ":base(global::WinRT.DerivedComposed.Instance)" : "", + bind(class_type, false, false), + cache_object, + method.Name(), + bind_list(", ", params_without_objects), + [&](writer& w) {w.write("%", params_without_objects.empty() ? " " : ", "); }, + default_interface_abi_name, + default_interface_abi_name, + bind(class_type)); + } + else + { + w.write(R"( +% %(%)% +{ +object baseInspectable = this.GetType() != typeof(%) ? this : null; +IntPtr composed = %.%(%%baseInspectable, out IntPtr ptr); +using IObjectReference composedRef = ObjectReference.Attach(ref composed); +try +{ +_inner = ComWrappersSupport.GetObjectReferenceForInterface(ptr); +_defaultLazy = new Lazy<%>(() => (%)this); + +ComWrappersSupport.RegisterObjectForInterface(this, ThisPtr); +} +finally +{ +MarshalInspectable.DisposeAbi(ptr); +} +} +)", + visibility, + class_type.TypeName(), + bind_list(", ", params_without_objects), + has_base_type ? ":base(global::WinRT.DerivedComposed.Instance)" : "", + bind(class_type, false, false), + cache_object, + method.Name(), + bind_list(", ", params_without_objects), + [&](writer& w) {w.write("%", params_without_objects.empty() ? " " : ", "); }, + default_interface_name, + default_interface_name); + } } } @@ -4560,7 +4597,7 @@ _lazyInterfaces = new Dictionary() [global::WinRT.ObjectReferenceWrapper(nameof(_inner))] %public %class %%, IWinRTObject, IEquatable<%> { -public %IntPtr ThisPtr => _inner.ThisPtr; +private IntPtr ThisPtr => _inner.ThisPtr; private IObjectReference _inner = null; private readonly Lazy<%> _defaultLazy; @@ -4603,7 +4640,6 @@ private % AsInternal(InterfaceTag<%> _) => _default; type_name, bind(type, base_semantics, true), type_name, - derived_new, default_interface_name, default_interface_name, bind(type), From bcaf88eb1e70ea6fc6e7fe7dbed2d9f07cf2438f Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Fri, 14 Aug 2020 10:08:26 -0700 Subject: [PATCH 09/23] Use equality functions instead of ThisPtr. --- UnitTest/TestComponentCSharp_Tests.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/UnitTest/TestComponentCSharp_Tests.cs b/UnitTest/TestComponentCSharp_Tests.cs index fa848d423..249c6bd13 100644 --- a/UnitTest/TestComponentCSharp_Tests.cs +++ b/UnitTest/TestComponentCSharp_Tests.cs @@ -738,7 +738,7 @@ public void TestClassGeneric() { var obj = objs[i]; Assert.Same(obj, TestObject); - Assert.Equal(TestObject.ThisPtr, objs[i].ThisPtr); + Assert.Equal(TestObject, objs[i]); } } [Fact] @@ -1498,7 +1498,8 @@ public void WeakReferenceOfNativeObjectRehydratedAfterWrapperIsCollected() [Fact] public void TestUnwrapInspectable() { - var inspectable = IInspectable.FromAbi(TestObject.ThisPtr); + using var objRef = MarshalInspectable.CreateMarshaler(TestObject); + var inspectable = IInspectable.FromAbi(objRef.ThisPtr); Assert.True(ComWrappersSupport.TryUnwrapObject(inspectable, out _)); } From cc3044841bd2995eadaf26e9256baf72428f3207 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Fri, 14 Aug 2020 11:19:02 -0700 Subject: [PATCH 10/23] Implement static interface support by using dynamic casting under the hood via an internal IInspectable instance. --- WinRT.Runtime/IWinRTObject.net5.cs | 9 ++++++--- cswinrt/code_writers.h | 17 ++++++++--------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/WinRT.Runtime/IWinRTObject.net5.cs b/WinRT.Runtime/IWinRTObject.net5.cs index ae9686a80..99ea26931 100644 --- a/WinRT.Runtime/IWinRTObject.net5.cs +++ b/WinRT.Runtime/IWinRTObject.net5.cs @@ -15,7 +15,7 @@ bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfac } Type type = Type.GetTypeFromHandle(interfaceType); Type helperType = type.FindHelperType(); - if (helperType is null) + if (helperType is null || !helperType.IsInterface) { return false; } @@ -55,10 +55,13 @@ bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfac RuntimeTypeHandle IDynamicInterfaceCastable.GetInterfaceImplementation(RuntimeTypeHandle interfaceType) { - return Type.GetTypeFromHandle(interfaceType).GetHelperType().TypeHandle; + var helperType = Type.GetTypeFromHandle(interfaceType).GetHelperType(); + if (helperType.IsInterface) + return helperType.TypeHandle; + return default; } - protected IObjectReference NativeObject { get; } + IObjectReference NativeObject { get; } protected ConcurrentDictionary QueryInterfaceCache { get; } diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index cab707224..b8f5609fa 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -1217,7 +1217,7 @@ using IObjectReference composedRef = ObjectReference.Attach(ref c try { _inner = ComWrappersSupport.GetObjectReferenceForInterface(ptr); -_defaultLazy = new Lazy<%>(() => (%)this); +_defaultLazy = new Lazy<%>(() => (%)new IInspectable(_inner)); ComWrappersSupport.RegisterObjectForInterface(this, ThisPtr); } @@ -1646,7 +1646,7 @@ private % AsInternal(InterfaceTag<%> _) => ((Lazy<%>)_lazyInterfaces[typeof(%)]) else { w.write(R"( -private % AsInternal(InterfaceTag<%> _) => (%)(object)this; +private % AsInternal(InterfaceTag<%> _) => (%)(object)_default; )", interface_name, interface_name, @@ -4403,7 +4403,7 @@ if (IsOverridableInterface(iid) || typeof(global::WinRT.IInspectable).GUID == ii return global::System.Runtime.InteropServices.CustomQueryInterfaceResult.NotHandled; } -if (GetReferenceForQI().TryAs(iid, out ObjectReference objRef) >= 0) +if (%.TryAs(iid, out ObjectReference objRef) >= 0) { using (objRef) { @@ -4450,7 +4450,8 @@ return global::System.Runtime.InteropServices.CustomQueryInterfaceResult.NotHand { w.write("false"); } - })); + }), + settings.netstandard_compat ? "GetReferenceForQI()" : "((IWinRTObject)this).NativeObject"); } void write_class_netstandard(writer& w, TypeDef const& type) @@ -4619,7 +4620,7 @@ return new %(objRef); % %(IObjectReference objRef)% { _inner = objRef.As<%.Vftbl>(); -_defaultLazy = new Lazy<%>(() => (%)(object)this); +_defaultLazy = new Lazy<%>(() => (%)new global::WinRT.IInspectable(_inner)); } public static bool operator ==(% x, % y) => (x?.ThisPtr ?? IntPtr.Zero) == (y?.ThisPtr ?? IntPtr.Zero); @@ -4670,7 +4671,7 @@ private % AsInternal(InterfaceTag<%> _) => _default; w.write(R"( protected %(global::WinRT.DerivedComposed _)% { -_defaultLazy = new Lazy<%>(() => (%)(object)this); +_defaultLazy = new Lazy<%>(() => (%)new IInspectable(((IWinRTObject)this).NativeObject)); })", type.TypeName(), has_base_type ? ":base(_)" : "", @@ -4679,9 +4680,7 @@ default_interface_name); } w.write(R"( -private IObjectReference GetReferenceForQI() => _inner; - -IObjectReference IWinRTObject.NativeObject => GetReferenceForQI(); +IObjectReference IWinRTObject.NativeObject => _inner; global::System.Collections.Concurrent.ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new();)"); }), From 1f2efee68e24bb6cdb7aab17477e8709024f5066 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Fri, 14 Aug 2020 14:00:44 -0700 Subject: [PATCH 11/23] Update to LangVersion preview --- Projections/WinUI/WinUI.csproj | 7 +------ Projections/Windows/Windows.csproj | 2 +- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Projections/WinUI/WinUI.csproj b/Projections/WinUI/WinUI.csproj index 0097e3c07..2ccb93b24 100644 --- a/Projections/WinUI/WinUI.csproj +++ b/Projections/WinUI/WinUI.csproj @@ -3,7 +3,7 @@ netstandard2.0;net5.0 x64;x86 - 8 + preview @@ -12,11 +12,6 @@ 8305;0618 - - full - true - - diff --git a/Projections/Windows/Windows.csproj b/Projections/Windows/Windows.csproj index 1e5a94f60..17a0c911b 100644 --- a/Projections/Windows/Windows.csproj +++ b/Projections/Windows/Windows.csproj @@ -3,7 +3,7 @@ netstandard2.0;net5.0 x64;x86 - 8 + preview From 1f4d86980ea3d94f47ed61fcf204f376478aec66 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Fri, 14 Aug 2020 14:02:23 -0700 Subject: [PATCH 12/23] Fix projected required interface implementations and handle default interfaces of runtime classes such that they can live in different projections and compile with only the public contract exposed. --- cswinrt/code_writers.h | 79 ++++++++++++++++++++++++++++++++---------- 1 file changed, 60 insertions(+), 19 deletions(-) diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index b8f5609fa..82847a6f7 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -2620,7 +2620,7 @@ global::System.Collections.Concurrent.ConcurrentDictionary(signature), bind([&](writer& w) { @@ -2731,11 +2731,11 @@ remove => %.Unsubscribe(value); return; } - if (auto mapping = get_mapped_type(iface.TypeNamespace(), iface.TypeName()); mapping && emit_mapped_type_helpers) + if (auto mapping = get_mapped_type(iface.TypeNamespace(), iface.TypeName())) { auto remove_enumerable = [&](std::string generic_enumerable = "") { - required_interfaces[std::move("global::System.Collections.IEnumerable")] = {}; + required_interfaces["global::System.Collections.IEnumerable"] = {}; if(generic_enumerable.empty()) return; required_interfaces[std::move(generic_enumerable)] = {}; }; @@ -2745,7 +2745,10 @@ remove => %.Unsubscribe(value); auto element = w.write_temp("%", bind(0)); required_interfaces[std::move(interface_name)] = { - w.write_temp("%", bind("_iterableToEnumerable", true)), + w.write_temp("%", bind( + emit_mapped_type_helpers ? "_iterableToEnumerable" + : w.write_temp("((global::System.Collections.Generic.IEnumerable<%>)(IWinRTObject)this)", element), + true)), w.write_temp("ABI.System.Collections.Generic.IEnumerable<%>", element), "_iterableToEnumerable" }; @@ -2756,7 +2759,10 @@ remove => %.Unsubscribe(value); auto element = w.write_temp("%", bind(0)); required_interfaces[std::move(interface_name)] = { - w.write_temp("%", bind("_iteratorToEnumerator")), + w.write_temp("%", bind( + emit_mapped_type_helpers ? "_iteratorToEnumerator" + : w.write_temp("((global::System.Collections.Generic.IEnumerator<%>)(IWinRTObject)this)", element) + )), w.write_temp("ABI.System.Collections.Generic.IEnumerator<%>", element), "_iteratorToEnumerator" }; @@ -2767,7 +2773,10 @@ remove => %.Unsubscribe(value); auto value = w.write_temp("%", bind(1)); required_interfaces[std::move(interface_name)] = { - w.write_temp("%", bind("_mapViewToReadOnlyDictionary", true)), + w.write_temp("%", bind( + emit_mapped_type_helpers ? "_mapViewToReadOnlyDictionary" + : w.write_temp("((global::System.Collections.Generic.IReadOnlyDictionary<%, %>)(IWinRTObject)this)", key, value), + true)), w.write_temp("ABI.System.Collections.Generic.IReadOnlyDictionary<%, %>", key, value), "_mapViewToReadOnlyDictionary" }; @@ -2779,7 +2788,10 @@ remove => %.Unsubscribe(value); auto value = w.write_temp("%", bind(1)); required_interfaces[std::move(interface_name)] = { - w.write_temp("%", bind("_mapToDictionary", true)), + w.write_temp("%", bind( + emit_mapped_type_helpers ? "_mapToDictionary" + : w.write_temp("((global::System.Collections.Generic.IDictionary<%, %>)(IWinRTObject)this)", key, value), + true)), w.write_temp("ABI.System.Collections.Generic.IDictionary<%, %>", key, value), "_mapToDictionary" }; @@ -2790,7 +2802,10 @@ remove => %.Unsubscribe(value); auto element = w.write_temp("%", bind(0)); required_interfaces[std::move(interface_name)] = { - w.write_temp("%", bind("_vectorViewToReadOnlyList", true)), + w.write_temp("%", bind( + emit_mapped_type_helpers ? "_vectorViewToReadOnlyList" + : w.write_temp("((global::System.Collections.Generic.IReadOnlyList<%>)(IWinRTObject)this)", element), + true)), w.write_temp("ABI.System.Collections.Generic.IReadOnlyList<%>", element), "_vectorViewToReadOnlyList" }; @@ -2801,7 +2816,10 @@ remove => %.Unsubscribe(value); auto element = w.write_temp("%", bind(0)); required_interfaces[std::move(interface_name)] = { - w.write_temp("%", bind("_vectorToList", true)), + w.write_temp("%", bind( + emit_mapped_type_helpers ? "_vectorToList" + : w.write_temp("((global::System.Collections.Generic.IList<%>)(IWinRTObject)this)", element), + true)), w.write_temp("ABI.System.Collections.Generic.IList<%>", element), "_vectorToList" }; @@ -2811,7 +2829,9 @@ remove => %.Unsubscribe(value); { required_interfaces[std::move(interface_name)] = { - w.write_temp("%", bind("_bindableIterableToEnumerable")), + w.write_temp("%", bind( + emit_mapped_type_helpers ? "_bindableIterableToEnumerable" + : "((global::System.Collections.IEnumerable)(IWinRTObject)this)")), "ABI.System.Collections.IEnumerable", "_bindableIterableToEnumerable" }; @@ -2820,7 +2840,10 @@ remove => %.Unsubscribe(value); { required_interfaces[std::move(interface_name)] = { - w.write_temp("%", bind("_bindableVectorToList", true)), + w.write_temp("%", bind( + emit_mapped_type_helpers ? "_bindableVectorToList" + : "((global::System.Collections.IList)(IWinRTObject)this)", + true)), "ABI.System.Collections.IList", "_bindableVectorToList" }; @@ -2830,7 +2853,7 @@ remove => %.Unsubscribe(value); { required_interfaces[std::move(interface_name)] = { - w.write_temp("%", bind("As()")) + w.write_temp("%", bind(emit_mapped_type_helpers ? "As()" : "((global::System.IDisposable)(IWinRTObject)this)")) }; } return; @@ -4590,7 +4613,6 @@ _lazyInterfaces = new Dictionary() auto type_name = write_type_name_temp(w, type); auto default_interface_name = get_default_interface_name(w, type, false); - auto default_interface_abi_name = get_default_interface_name(w, type, true); auto base_semantics = get_type_semantics(type.Extends()); auto derived_new = std::holds_alternative(base_semantics) ? "" : "new "; @@ -4619,7 +4641,7 @@ return new %(objRef); % %(IObjectReference objRef)% { -_inner = objRef.As<%.Vftbl>(); +_inner = objRef.As(GuidGenerator.GetIID(typeof(%).GetHelperType())); _defaultLazy = new Lazy<%>(() => (%)new global::WinRT.IInspectable(_inner)); } @@ -4653,7 +4675,7 @@ private % AsInternal(InterfaceTag<%> _) => _default; type.Flags().Sealed() ? "internal" : "protected internal", type_name, bind(base_semantics), - default_interface_abi_name, + default_interface_name, default_interface_name, default_interface_name, // Equality operators @@ -4699,12 +4721,11 @@ global::System.Collections.Concurrent.ConcurrentDictionary obj is null ? null : MarshalInspectable.CreateMarshaler(obj).As<%.Vftbl>(); +% public static IntPtr GetAbi(IObjectReference value) => value is null ? IntPtr.Zero : MarshalInterfaceHelper.GetAbi(value); public static % FromAbi(IntPtr thisPtr) => %.FromAbi(thisPtr); public static IntPtr FromManaged(% obj) => obj is null ? IntPtr.Zero : CreateMarshaler(obj).GetRef(); @@ -4719,8 +4740,28 @@ public static unsafe void DisposeAbiArray(object box) => MarshalInspectable.Disp } )", abi_type_name, - projected_type_name, - default_interface_abi_name, + bind([&](writer& w) + { + bool is_exclusive_to_default = false; + for_typedef(w, get_type_semantics(get_default_interface(type)), [&](auto&& type) + { + is_exclusive_to_default = is_exclusive_to(type); + }); + if (is_exclusive_to_default) + { + auto default_interface_abi_name = get_default_interface_name(w, type, true); + w.write("public static IObjectReference CreateMarshaler(% obj) => obj is null ? null : MarshalInspectable.CreateMarshaler(obj).As<%.Vftbl>();", + projected_type_name, + default_interface_abi_name); + } + else + { + auto default_interface_name = get_default_interface_name(w, type, false); + w.write("public static IObjectReference CreateMarshaler(% obj) => obj is null ? null : MarshalInterface<%>.CreateMarshaler(obj);", + projected_type_name, + default_interface_name); + } + }), projected_type_name, projected_type_name, projected_type_name, From 25e4e4bbf462d63bc8dfefb0d4a698d252308221 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Fri, 14 Aug 2020 14:03:49 -0700 Subject: [PATCH 13/23] Use Spans instead of LINQ to improve perf in Guid generation (startup perf). --- WinRT.Runtime/GuidGenerator.cs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/WinRT.Runtime/GuidGenerator.cs b/WinRT.Runtime/GuidGenerator.cs index 1f927aac2..1dbc1418a 100644 --- a/WinRT.Runtime/GuidGenerator.cs +++ b/WinRT.Runtime/GuidGenerator.cs @@ -98,7 +98,7 @@ public static string GetSignature(Type type) return "{" + type.GUID.ToString() + "}"; } - private static Guid encode_guid(byte[] data) + private static Guid encode_guid(Span data) { if (BitConverter.IsLittleEndian) { @@ -120,7 +120,11 @@ private static Guid encode_guid(byte[] data) // encode rfc clock/reserved field data[8] = (byte)((data[8] & 0x3f) | 0x80); } - return new Guid(data.Take(16).ToArray()); +#if NETSTANDARD2_0 + return new Guid(data.Slice(0, 16).ToArray()); +#else + return new Guid(data[0..16]); +#endif } private static Guid wrt_pinterface_namespace = new Guid("d57af411-737b-c042-abae-878b1e16adee"); @@ -132,11 +136,19 @@ public static Guid CreateIID(Type type) { return new Guid(sig); } +#if NETSTANDARD2_0 var data = wrt_pinterface_namespace.ToByteArray().Concat(UTF8Encoding.UTF8.GetBytes(sig)).ToArray(); +#else + var maxBytes = UTF8Encoding.UTF8.GetMaxByteCount(sig.Length); + + var data = new byte[16 /* Number of bytes in a GUID */ + maxBytes]; + Span dataSpan = data; + wrt_pinterface_namespace.TryWriteBytes(dataSpan); + UTF8Encoding.UTF8.GetBytes(sig, dataSpan[16..]); +#endif using (SHA1 sha = new SHA1CryptoServiceProvider()) { - var hash = sha.ComputeHash(data); - return encode_guid(hash); + return encode_guid(sha.ComputeHash(data)); } } } From b58f37d5af2a50b1480059bb8fb9cf70f3757c23 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Fri, 14 Aug 2020 14:53:59 -0700 Subject: [PATCH 14/23] Get WinUI projection compiling with no new warnings. --- cswinrt/code_writers.h | 307 +++++++++++++++++++++++------------------ 1 file changed, 171 insertions(+), 136 deletions(-) diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index 82847a6f7..1a1719119 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -1304,13 +1304,15 @@ IEnumerator IEnumerable.GetEnumerator() => %.GetEnumerator(); target); } - void write_enumerable_members(writer& w, std::string_view target, bool include_nongeneric) + void write_enumerable_members(writer& w, std::string_view target, bool include_nongeneric, bool emit_explicit) { auto element = w.write_temp("%", bind(0)); + auto self = emit_explicit ? w.write_temp("global::System.Collections.Generic.IEnumerable<%>.", element) : ""; + auto visibility = emit_explicit ? "" : "public "; w.write(R"( -public IEnumerator<%> GetEnumerator() => %.GetEnumerator(); +%IEnumerator<%> %GetEnumerator() => %.GetEnumerator(); )", - element, target); + visibility, element, self, target); if (!include_nongeneric) return; w.write(R"( @@ -1318,40 +1320,45 @@ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); )"); } - void write_enumerator_members(writer& w, std::string_view target) + void write_enumerator_members(writer& w, std::string_view target, bool emit_explicit) { auto element = w.write_temp("%", bind(0)); + auto self = emit_explicit ? w.write_temp("global::System.Collections.Generic.IEnumerator<%>.", element) : ""; + auto visibility = emit_explicit ? "" : "public "; + w.write(R"( -public bool MoveNext() => %.MoveNext(); -public void Reset() => %.Reset(); -public void Dispose() => %.Dispose(); -public % Current => %.Current; +%bool %MoveNext() => %.MoveNext(); +%void %Reset() => %.Reset(); +%void %Dispose() => %.Dispose(); +%% %Current => %.Current; object IEnumerator.Current => Current; )", - target, - target, - target, - element, target); + visibility, self, target, + visibility, self, target, + visibility, self, target, + visibility, element, self, target); } - void write_readonlydictionary_members(writer& w, std::string_view target, bool include_enumerable) + void write_readonlydictionary_members(writer& w, std::string_view target, bool include_enumerable, bool emit_explicit) { auto key = w.write_temp("%", bind(0)); auto value = w.write_temp("%", bind(1)); + auto self = emit_explicit ? w.write_temp("global::System.Collections.Generic.IReadOnlyDictionary<%, %>.", key, value) : ""; + auto visibility = emit_explicit ? "" : "public "; w.write(R"( -public IEnumerable<%> Keys => %.Keys; -public IEnumerable<%> Values => %.Values; -public int Count => %.Count; -public % this[% key] => %[key]; -public bool ContainsKey(% key) => %.ContainsKey(key); -public bool TryGetValue(% key, out % value) => %.TryGetValue(key, out value); +%IEnumerable<%> %Keys => %.Keys; +%IEnumerable<%> %Values => %.Values; +%int %Count => %.Count; +%% %this[% key] => %[key]; +%bool %ContainsKey(% key) => %.ContainsKey(key); +%bool %TryGetValue(% key, out % value) => %.TryGetValue(key, out value); )", - key, target, - value, target, - target, - value, key, target, - key, target, - key, value, target); + visibility, key, self, target, + visibility, value, self, target, + visibility, self, target, + visibility, value, self, key, target, + visibility, self, key, target, + visibility, self, key, value, target); if (!include_enumerable) return; w.write(R"( @@ -1361,110 +1368,123 @@ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); key, value, target); } - void write_dictionary_members(writer& w, std::string_view target, bool include_enumerable) + void write_dictionary_members(writer& w, std::string_view target, bool include_enumerable, bool emit_explicit) { auto key = w.write_temp("%", bind(0)); auto value = w.write_temp("%", bind(1)); + auto self = emit_explicit ? w.write_temp("global::System.Collections.Generic.IReadOnlyDictionary<%, %>.", key, value) : ""; + auto visibility = emit_explicit ? "" : "public "; w.write(R"( -public ICollection<%> Keys => %.Keys; -public ICollection<%> Values => %.Values; -public int Count => %.Count; -public bool IsReadOnly => %.IsReadOnly; -public % this[% key] +%ICollection<%> %Keys => %.Keys; +%ICollection<%> %Values => %.Values; +%int %Count => %.Count; +%bool %IsReadOnly => %.IsReadOnly; +%% %this[% key] { get => %[key]; set => %[key] = value; } -public void Add(% key, % value) => %.Add(key, value); -public bool ContainsKey(% key) => %.ContainsKey(key); -public bool Remove(% key) => %.Remove(key); -public bool TryGetValue(% key, out % value) => %.TryGetValue(key, out value); -public void Add(KeyValuePair<%, %> item) => %.Add(item); -public void Clear() => %.Clear(); -public bool Contains(KeyValuePair<%, %> item) => %.Contains(item); -public void CopyTo(KeyValuePair<%, %>[] array, int arrayIndex) => %.CopyTo(array, arrayIndex); +%void %Add(% key, % value) => %.Add(key, value); +%bool %ContainsKey(% key) => %.ContainsKey(key); +%bool %Remove(% key) => %.Remove(key); +%bool %TryGetValue(% key, out % value) => %.TryGetValue(key, out value); +%void %Add(KeyValuePair<%, %> item) => %.Add(item); +%void %Clear() => %.Clear(); +%bool %Contains(KeyValuePair<%, %> item) => %.Contains(item); +%void %CopyTo(KeyValuePair<%, %>[] array, int arrayIndex) => %.CopyTo(array, arrayIndex); bool ICollection>.Remove(KeyValuePair<%, %> item) => %.Remove(item); )", - key, target, - value, target, - target, - target, - value, key, target, target, - key, value, target, - key, target, - key, target, - key, value, target, - key, value, target, - target, - key, value, target, - key, value, target, + visibility, key, self, target, + visibility, value, self, target, + visibility, self, target, + visibility, self, target, + visibility, value, self, key, target, target, + visibility, self, key, value, target, + visibility, self, key, target, + visibility, self, key, target, + visibility, self, key, value, target, + visibility, self, key, value, target, + visibility, self, target, + visibility, self, key, value, target, + visibility, self, key, value, target, key, value, key, value, target); if (!include_enumerable) return; + auto enumerable_type = emit_explicit ? w.write_temp("IEnumerable>.", key, value) : ""; w.write(R"( -public IEnumerator> GetEnumerator() => %.GetEnumerator(); +%IEnumerator> %GetEnumerator() => %.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); )", - key, value, target); + visibility, key, value, enumerable_type, target); } - void write_readonlylist_members(writer& w, std::string_view target, bool include_enumerable) + void write_readonlylist_members(writer& w, std::string_view target, bool include_enumerable, bool emit_explicit) { auto element = w.write_temp("%", bind(0)); + auto self = emit_explicit ? w.write_temp("global::System.Collections.Generic.IReadOnlyList<%>.", element) : ""; + auto ireadonlycollection = emit_explicit ? w.write_temp("global::System.Collections.Generic.IReadOnlyCollection<%>.", element) : ""; + auto visibility = emit_explicit ? "" : "public "; w.write(R"( -public int Count => %.Count; -[global::System.Runtime.CompilerServices.IndexerName("ReadOnlyListItem")] -public % this[int index] => %[index]; +%int %Count => %.Count; +% +%% %this[int index] => %[index]; )", - target, - element, target); + visibility, ireadonlycollection, target, + !emit_explicit ? R"([global::System.Runtime.CompilerServices.IndexerName("ReadOnlyListItem")])" : "", + visibility, element, self, target); if (!include_enumerable) return; + auto enumerable_type = emit_explicit ? w.write_temp("IEnumerable<%>.", element) : ""; w.write(R"( -public IEnumerator<%> GetEnumerator() => %.GetEnumerator(); +%IEnumerator<%> %GetEnumerator() => %.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); )", - element, target); + visibility, element, enumerable_type, target); } - void write_nongeneric_list_members(writer& w, std::string_view target, bool include_enumerable) + void write_nongeneric_list_members(writer& w, std::string_view target, bool include_enumerable, bool emit_explicit) { + auto self = emit_explicit ? "global::System.Collections.IList." : ""; + auto icollection = emit_explicit ? "global::System.Collections.ICollection." : ""; + auto visibility = emit_explicit ? "" : "public "; w.write(R"( -public int Count => %.Count; -public bool IsSynchronized => %.IsSynchronized; -public object SyncRoot => %.SyncRoot; -public void CopyTo(Array array, int index) => %.CopyTo(array, index); -[global::System.Runtime.CompilerServices.IndexerName("NonGenericListItem")] -public object this[int index] +%int %Count => %.Count; +%bool %IsSynchronized => %.IsSynchronized; +%object %SyncRoot => %.SyncRoot; +%void %CopyTo(Array array, int index) => %.CopyTo(array, index); +% +%object %this[int index] { get => %[index]; set => %[index] = value; } -public bool IsFixedSize => %.IsFixedSize; -public bool IsReadOnly => %.IsReadOnly; -public int Add(object value) => %.Add(value); -public void Clear() => %.Clear(); -public bool Contains(object value) => %.Contains(value); -public int IndexOf(object value) => %.IndexOf(value); -public void Insert(int index, object value) => %.Insert(index, value); -public void Remove(object value) => %.Remove(value); -public void RemoveAt(int index) => %.RemoveAt(index); +%bool %IsFixedSize => %.IsFixedSize; +%bool %IsReadOnly => %.IsReadOnly; +%int %Add(object value) => %.Add(value); +%void %Clear() => %.Clear(); +%bool %Contains(object value) => %.Contains(value); +%int %IndexOf(object value) => %.IndexOf(value); +%void %Insert(int index, object value) => %.Insert(index, value); +%void %Remove(object value) => %.Remove(value); +%void %RemoveAt(int index) => %.RemoveAt(index); )", + visibility, icollection, target, + visibility, icollection, target, + visibility, icollection, target, + visibility, icollection, target, + !emit_explicit ? R"([global::System.Runtime.CompilerServices.IndexerName("NonGenericListItem")])" : "", + visibility, self, target, target, - target, - target, - target, - target, - target, - target, - target, - target, - target, - target, - target, - target, - target); + visibility, self, target, + visibility, self, target, + visibility, self, target, + visibility, self, target, + visibility, self, target, + visibility, self, target, + visibility, self, target, + visibility, self, target, + visibility, self, target); if (!include_enumerable) return; w.write(R"( @@ -1473,80 +1493,87 @@ IEnumerator IEnumerable.GetEnumerator() => %.GetEnumerator(); target); } - void write_list_members(writer& w, std::string_view target, bool include_enumerable) + void write_list_members(writer& w, std::string_view target, bool include_enumerable, bool emit_explicit) { auto element = w.write_temp("%", bind(0)); + auto self = emit_explicit ? w.write_temp("global::System.Collections.Generic.IList<%>.", element) : ""; + auto icollection = emit_explicit ? w.write_temp("global::System.Collections.Generic.ICollection<%>.", element) : ""; + auto visibility = emit_explicit ? "" : "public "; w.write(R"( -public int Count => %.Count; -public bool IsReadOnly => %.IsReadOnly; -[global::System.Runtime.CompilerServices.IndexerName("ListItem")] -public % this[int index] +%int %Count => %.Count; +%bool %IsReadOnly => %.IsReadOnly; +% +%% %this[int index] { get => %[index]; set => %[index] = value; } -public int IndexOf(% item) => %.IndexOf(item); -public void Insert(int index, % item) => %.Insert(index, item); -public void RemoveAt(int index) => %.RemoveAt(index); -public void Add(% item) => %.Add(item); -public void Clear() => %.Clear(); -public bool Contains(% item) => %.Contains(item); -public void CopyTo(%[] array, int arrayIndex) => %.CopyTo(array, arrayIndex); -public bool Remove(% item) => %.Remove(item); +%int %IndexOf(% item) => %.IndexOf(item); +%void %Insert(int index, % item) => %.Insert(index, item); +%void %RemoveAt(int index) => %.RemoveAt(index); +%void %Add(% item) => %.Add(item); +%void %Clear() => %.Clear(); +%bool %Contains(% item) => %.Contains(item); +%void %CopyTo(%[] array, int arrayIndex) => %.CopyTo(array, arrayIndex); +%bool %Remove(% item) => %.Remove(item); )", - target, - target, - element, target, target, - element, target, - element, target, - target, - element, target, - target, - element, target, - element, target, - element, target); + visibility, icollection, target, + visibility, icollection, target, + !emit_explicit ? R"([global::System.Runtime.CompilerServices.IndexerName("ListItem")])" : "", + visibility, element, self, target, target, + visibility, self, element, target, + visibility, self, element, target, + visibility, self, target, + visibility, icollection, element, target, + visibility, icollection, target, + visibility, icollection, element, target, + visibility, icollection, element, target, + visibility, icollection, element, target); if (!include_enumerable) return; + auto enumerable_type = emit_explicit ? w.write_temp("IEnumerable<%>.", element) : ""; w.write(R"( -public IEnumerator<%> GetEnumerator() => %.GetEnumerator(); +%IEnumerator<%> %GetEnumerator() => %.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); )", - element, target); + visibility, element, enumerable_type, target); } - void write_idisposable_members(writer& w, std::string_view target) + void write_idisposable_members(writer& w, std::string_view target, bool emit_explicit) { + auto self = emit_explicit ? "global::System.IDisposable." : ""; + auto visibility = emit_explicit ? "" : "public "; w.write(R"( -public void Dispose() => %.Dispose(); +%void %Dispose() => %.Dispose(); )", -target); + visibility, self, target); } void write_custom_mapped_type_members(writer& w, std::string_view target, mapped_type const& mapping) { if (mapping.abi_name == "IIterable`1") { - write_enumerable_members(w, target, true); + write_enumerable_members(w, target, true, false); } else if (mapping.abi_name == "IIterator`1") { - write_enumerator_members(w, target); + write_enumerator_members(w, target, false); } else if (mapping.abi_name == "IMapView`2") { - write_readonlydictionary_members(w, target, false); + write_readonlydictionary_members(w, target, false, false); } else if (mapping.abi_name == "IMap`2") { - write_dictionary_members(w, target, false); + write_dictionary_members(w, target, false, false); } else if (mapping.abi_name == "IVectorView`1") { - write_readonlylist_members(w, target, false); + write_readonlylist_members(w, target, false, false); } else if (mapping.abi_name == "IVector`1") { - write_list_members(w, target, false); + write_list_members(w, target, false, false); } else if (mapping.abi_name == "IBindableIterable") { @@ -1554,11 +1581,11 @@ target); } else if (mapping.abi_name == "IBindableVector") { - write_nongeneric_list_members(w, target, false); + write_nongeneric_list_members(w, target, false, false); } else if (mapping.mapped_namespace == "System" && mapping.mapped_name == "IDisposable") { - write_idisposable_members(w, target); + write_idisposable_members(w, target, false); } } @@ -2748,7 +2775,8 @@ remove => %.Unsubscribe(value); w.write_temp("%", bind( emit_mapped_type_helpers ? "_iterableToEnumerable" : w.write_temp("((global::System.Collections.Generic.IEnumerable<%>)(IWinRTObject)this)", element), - true)), + true, + !emit_mapped_type_helpers)), w.write_temp("ABI.System.Collections.Generic.IEnumerable<%>", element), "_iterableToEnumerable" }; @@ -2761,7 +2789,8 @@ remove => %.Unsubscribe(value); { w.write_temp("%", bind( emit_mapped_type_helpers ? "_iteratorToEnumerator" - : w.write_temp("((global::System.Collections.Generic.IEnumerator<%>)(IWinRTObject)this)", element) + : w.write_temp("((global::System.Collections.Generic.IEnumerator<%>)(IWinRTObject)this)", element), + !emit_mapped_type_helpers )), w.write_temp("ABI.System.Collections.Generic.IEnumerator<%>", element), "_iteratorToEnumerator" @@ -2776,7 +2805,8 @@ remove => %.Unsubscribe(value); w.write_temp("%", bind( emit_mapped_type_helpers ? "_mapViewToReadOnlyDictionary" : w.write_temp("((global::System.Collections.Generic.IReadOnlyDictionary<%, %>)(IWinRTObject)this)", key, value), - true)), + true, + !emit_mapped_type_helpers)), w.write_temp("ABI.System.Collections.Generic.IReadOnlyDictionary<%, %>", key, value), "_mapViewToReadOnlyDictionary" }; @@ -2791,7 +2821,8 @@ remove => %.Unsubscribe(value); w.write_temp("%", bind( emit_mapped_type_helpers ? "_mapToDictionary" : w.write_temp("((global::System.Collections.Generic.IDictionary<%, %>)(IWinRTObject)this)", key, value), - true)), + true, + !emit_mapped_type_helpers)), w.write_temp("ABI.System.Collections.Generic.IDictionary<%, %>", key, value), "_mapToDictionary" }; @@ -2805,7 +2836,8 @@ remove => %.Unsubscribe(value); w.write_temp("%", bind( emit_mapped_type_helpers ? "_vectorViewToReadOnlyList" : w.write_temp("((global::System.Collections.Generic.IReadOnlyList<%>)(IWinRTObject)this)", element), - true)), + true, + !emit_mapped_type_helpers)), w.write_temp("ABI.System.Collections.Generic.IReadOnlyList<%>", element), "_vectorViewToReadOnlyList" }; @@ -2819,7 +2851,8 @@ remove => %.Unsubscribe(value); w.write_temp("%", bind( emit_mapped_type_helpers ? "_vectorToList" : w.write_temp("((global::System.Collections.Generic.IList<%>)(IWinRTObject)this)", element), - true)), + true, + !emit_mapped_type_helpers)), w.write_temp("ABI.System.Collections.Generic.IList<%>", element), "_vectorToList" }; @@ -2843,7 +2876,8 @@ remove => %.Unsubscribe(value); w.write_temp("%", bind( emit_mapped_type_helpers ? "_bindableVectorToList" : "((global::System.Collections.IList)(IWinRTObject)this)", - true)), + true, + !emit_mapped_type_helpers)), "ABI.System.Collections.IList", "_bindableVectorToList" }; @@ -2853,7 +2887,8 @@ remove => %.Unsubscribe(value); { required_interfaces[std::move(interface_name)] = { - w.write_temp("%", bind(emit_mapped_type_helpers ? "As()" : "((global::System.IDisposable)(IWinRTObject)this)")) + w.write_temp("%", bind(emit_mapped_type_helpers ? "As()" : "((global::System.IDisposable)(IWinRTObject)this)", + !emit_mapped_type_helpers)) }; } return; From a02a72cc72ed678083487cf487f7d62359c46613 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Fri, 14 Aug 2020 16:19:16 -0700 Subject: [PATCH 15/23] Fix more collections so the Windows projection also builds. --- cswinrt/code_writers.h | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index 1a1719119..8bdcefc8c 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -1344,6 +1344,7 @@ object IEnumerator.Current => Current; auto key = w.write_temp("%", bind(0)); auto value = w.write_temp("%", bind(1)); auto self = emit_explicit ? w.write_temp("global::System.Collections.Generic.IReadOnlyDictionary<%, %>.", key, value) : ""; + auto ireadonlycollection = emit_explicit ? w.write_temp("global::System.Collections.Generic.IReadOnlyCollection>.", key, value ) : ""; auto visibility = emit_explicit ? "" : "public "; w.write(R"( %IEnumerable<%> %Keys => %.Keys; @@ -1355,7 +1356,7 @@ object IEnumerator.Current => Current; )", visibility, key, self, target, visibility, value, self, target, - visibility, self, target, + visibility, ireadonlycollection, target, visibility, value, self, key, target, visibility, self, key, target, visibility, self, key, value, target); @@ -1372,7 +1373,8 @@ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); { auto key = w.write_temp("%", bind(0)); auto value = w.write_temp("%", bind(1)); - auto self = emit_explicit ? w.write_temp("global::System.Collections.Generic.IReadOnlyDictionary<%, %>.", key, value) : ""; + auto self = emit_explicit ? w.write_temp("global::System.Collections.Generic.IDictionary<%, %>.", key, value) : ""; + auto icollection = emit_explicit ? w.write_temp("global::System.Collections.Generic.ICollection>.", key, value ) : ""; auto visibility = emit_explicit ? "" : "public "; w.write(R"( %ICollection<%> %Keys => %.Keys; @@ -1396,17 +1398,17 @@ bool ICollection>.Remove(KeyValuePair<%, %> item) => %.Remove )", visibility, key, self, target, visibility, value, self, target, - visibility, self, target, - visibility, self, target, + visibility, icollection, target, + visibility, icollection, target, visibility, value, self, key, target, target, visibility, self, key, value, target, visibility, self, key, target, visibility, self, key, target, visibility, self, key, value, target, - visibility, self, key, value, target, - visibility, self, target, - visibility, self, key, value, target, - visibility, self, key, value, target, + visibility, icollection, key, value, target, + visibility, icollection, target, + visibility, icollection, key, value, target, + visibility, icollection, key, value, target, key, value, key, value, target); if (!include_enumerable) return; From b5c3c3114117cabbf2fe8b94e0182772c4b20c3b Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Mon, 17 Aug 2020 15:41:33 -0700 Subject: [PATCH 16/23] Cache cast results in .NET 5 projection to regain some perf losses. --- WinRT.Runtime/IWinRTObject.net5.cs | 2 +- cswinrt/code_writers.h | 57 ++++++++++++++++++++++-------- 2 files changed, 44 insertions(+), 15 deletions(-) diff --git a/WinRT.Runtime/IWinRTObject.net5.cs b/WinRT.Runtime/IWinRTObject.net5.cs index 99ea26931..2d9fcb5f6 100644 --- a/WinRT.Runtime/IWinRTObject.net5.cs +++ b/WinRT.Runtime/IWinRTObject.net5.cs @@ -9,7 +9,7 @@ public interface IWinRTObject : IDynamicInterfaceCastable { bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented) { - if (QueryInterfaceCache.TryGetValue(interfaceType, out _)) + if (QueryInterfaceCache.ContainsKey(interfaceType)) { return true; } diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index 8bdcefc8c..51a454086 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -866,11 +866,22 @@ set => %.% = value; auto interface_name = write_type_name_temp(w, interface_type); auto interface_abi_name = write_type_name_temp(w, interface_type, "%", true); - w.write(R"( + if (settings.netstandard_compat) + { + w.write(R"( {typeof(%), new Lazy<%>(() => new %(GetReferenceForQI()))},)", - interface_name, - interface_abi_name, - interface_abi_name); + interface_name, + interface_abi_name, + interface_abi_name); + } + else + { + w.write(R"( +{typeof(%), new Lazy<%>(() => (%)(object)_default)},)", + interface_name, + interface_name, + interface_name); + } }); } } @@ -1218,6 +1229,9 @@ try { _inner = ComWrappersSupport.GetObjectReferenceForInterface(ptr); _defaultLazy = new Lazy<%>(() => (%)new IInspectable(_inner)); +_lazyInterfaces = new Dictionary() +{% +}; ComWrappersSupport.RegisterObjectForInterface(this, ThisPtr); } @@ -1237,7 +1251,8 @@ MarshalInspectable.DisposeAbi(ptr); bind_list(", ", params_without_objects), [&](writer& w) {w.write("%", params_without_objects.empty() ? " " : ", "); }, default_interface_name, - default_interface_name); + default_interface_name, + bind(class_type)); } } } @@ -1362,11 +1377,12 @@ object IEnumerator.Current => Current; visibility, self, key, value, target); if (!include_enumerable) return; + auto enumerable_type = emit_explicit ? w.write_temp("IEnumerable>.", key, value) : ""; w.write(R"( -public IEnumerator> GetEnumerator() => %.GetEnumerator(); +%IEnumerator> %GetEnumerator() => %.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); )", - key, value, target); + visibility, key, value, enumerable_type, target); } void write_dictionary_members(writer& w, std::string_view target, bool include_enumerable, bool emit_explicit) @@ -1675,8 +1691,9 @@ private % AsInternal(InterfaceTag<%> _) => ((Lazy<%>)_lazyInterfaces[typeof(%)]) else { w.write(R"( -private % AsInternal(InterfaceTag<%> _) => (%)(object)_default; +private % AsInternal(InterfaceTag<%> _) => ((Lazy<%>)_lazyInterfaces[typeof(%)]).Value; )", + interface_name, interface_name, interface_name, interface_name); @@ -4661,6 +4678,7 @@ private IntPtr ThisPtr => _inner.ThisPtr; private IObjectReference _inner = null; private readonly Lazy<%> _defaultLazy; +private readonly Dictionary _lazyInterfaces; private % _default => _defaultLazy.Value; % @@ -4680,6 +4698,9 @@ return new %(objRef); { _inner = objRef.As(GuidGenerator.GetIID(typeof(%).GetHelperType())); _defaultLazy = new Lazy<%>(() => (%)new global::WinRT.IInspectable(_inner)); +_lazyInterfaces = new Dictionary() +{% +}; } public static bool operator ==(% x, % y) => (x?.ThisPtr ?? IntPtr.Zero) == (y?.ThisPtr ?? IntPtr.Zero); @@ -4715,6 +4736,7 @@ private % AsInternal(InterfaceTag<%> _) => _default; default_interface_name, default_interface_name, default_interface_name, + bind(type), // Equality operators type_name, type_name, @@ -4731,17 +4753,24 @@ private % AsInternal(InterfaceTag<%> _) => _default; protected %(global::WinRT.DerivedComposed _)% { _defaultLazy = new Lazy<%>(() => (%)new IInspectable(((IWinRTObject)this).NativeObject)); +_lazyInterfaces = new Dictionary() +{% +}; })", -type.TypeName(), -has_base_type ? ":base(_)" : "", -default_interface_name, -default_interface_name); + type.TypeName(), + has_base_type ? ":base(_)" : "", + default_interface_name, + default_interface_name, + bind(type)); } w.write(R"( -IObjectReference IWinRTObject.NativeObject => _inner; - +IObjectReference IWinRTObject.NativeObject => _inner;)"); + if (!has_base_type) + { + w.write(R"( global::System.Collections.Concurrent.ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new();)"); + } }), default_interface_name, default_interface_name, From 597a024b61836abfffe3b7269f41e0c1e2505bd0 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Mon, 17 Aug 2020 16:14:19 -0700 Subject: [PATCH 17/23] Add support for IDynamicInterfaceCastable-based interfaces in RCW creation --- WinRT.Runtime/ComWrappersSupport.cs | 40 +--------------- WinRT.Runtime/ComWrappersSupport.net5.cs | 17 +++++++ .../ComWrappersSupport.netstandard2.0.cs | 46 +++++++++++++++++++ 3 files changed, 64 insertions(+), 39 deletions(-) diff --git a/WinRT.Runtime/ComWrappersSupport.cs b/WinRT.Runtime/ComWrappersSupport.cs index c08e69f7b..6bc759ed3 100644 --- a/WinRT.Runtime/ComWrappersSupport.cs +++ b/WinRT.Runtime/ComWrappersSupport.cs @@ -307,45 +307,7 @@ internal static Func CreateTypedRcwFactory(string runtimeC return CreateArrayFactory(implementationType); } - Type classType; - Type interfaceType; - Type vftblType; - if (implementationType.IsInterface) - { - classType = null; - interfaceType = implementationType.GetHelperType() ?? - throw new TypeLoadException($"Unable to find an ABI implementation for the type '{runtimeClassName}'"); - vftblType = interfaceType.FindVftblType() ?? throw new TypeLoadException($"Unable to find a vtable type for the type '{runtimeClassName}'"); - if (vftblType.IsGenericTypeDefinition) - { - vftblType = vftblType.MakeGenericType(interfaceType.GetGenericArguments()); - } - } - else - { - classType = implementationType; - interfaceType = Projections.GetDefaultInterfaceTypeForRuntimeClassType(classType); - if (interfaceType is null) - { - throw new TypeLoadException($"Unable to create a runtime wrapper for a WinRT object of type '{runtimeClassName}'. This type is not a projected type."); - } - vftblType = interfaceType.FindVftblType() ?? throw new TypeLoadException($"Unable to find a vtable type for the type '{runtimeClassName}'"); - } - - ParameterExpression[] parms = new[] { Expression.Parameter(typeof(IInspectable), "inspectable") }; - var createInterfaceInstanceExpression = Expression.New(interfaceType.GetConstructor(new[] { typeof(ObjectReference<>).MakeGenericType(vftblType) }), - Expression.Call(parms[0], - typeof(IInspectable).GetMethod(nameof(IInspectable.As)).MakeGenericMethod(vftblType))); - - if (classType is null) - { - return Expression.Lambda>(createInterfaceInstanceExpression, parms).Compile(); - } - - return Expression.Lambda>( - Expression.New(classType.GetConstructor(BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, new[] { interfaceType }, null), - createInterfaceInstanceExpression), - parms).Compile(); + return CreateFactoryForImplementationType(runtimeClassName, implementationType); } private static bool ShouldProvideIReference(object obj) diff --git a/WinRT.Runtime/ComWrappersSupport.net5.cs b/WinRT.Runtime/ComWrappersSupport.net5.cs index 3ec14b00e..98098b86e 100644 --- a/WinRT.Runtime/ComWrappersSupport.net5.cs +++ b/WinRT.Runtime/ComWrappersSupport.net5.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -97,6 +98,22 @@ public static void InitializeComWrappers(ComWrappers wrappers = null) } internal static Func GetTypedRcwFactory(string runtimeClassName) => TypedObjectFactoryCache.GetOrAdd(runtimeClassName, className => CreateTypedRcwFactory(className)); + + + private static Func CreateFactoryForImplementationType(string runtimeClassName, Type implementationType) + { + if (implementationType.IsInterface) + { + return obj => obj; + } + + ParameterExpression[] parms = new[] { Expression.Parameter(typeof(IInspectable), "inspectable") }; + + return Expression.Lambda>( + Expression.New(implementationType.GetConstructor(BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, new[] { typeof(IObjectReference) }, null), + Expression.Property(parms[0], nameof(WinRT.IInspectable.ObjRef))), + parms).Compile(); + } } public class DefaultComWrappers : ComWrappers diff --git a/WinRT.Runtime/ComWrappersSupport.netstandard2.0.cs b/WinRT.Runtime/ComWrappersSupport.netstandard2.0.cs index 15d340f00..95ebb9937 100644 --- a/WinRT.Runtime/ComWrappersSupport.netstandard2.0.cs +++ b/WinRT.Runtime/ComWrappersSupport.netstandard2.0.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Linq.Expressions; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; @@ -181,6 +183,50 @@ public RuntimeWrapperCleanup(IntPtr identityComObject, System.WeakReference CreateFactoryForImplementationType(string runtimeClassName, Type implementationType) + { + Type classType; + Type interfaceType; + Type vftblType; + if (implementationType.IsInterface) + { + classType = null; + interfaceType = implementationType.GetHelperType() ?? + throw new TypeLoadException($"Unable to find an ABI implementation for the type '{runtimeClassName}'"); + vftblType = interfaceType.FindVftblType() ?? throw new TypeLoadException($"Unable to find a vtable type for the type '{runtimeClassName}'"); + if (vftblType.IsGenericTypeDefinition) + { + vftblType = vftblType.MakeGenericType(interfaceType.GetGenericArguments()); + } + } + else + { + classType = implementationType; + interfaceType = Projections.GetDefaultInterfaceTypeForRuntimeClassType(classType); + if (interfaceType is null) + { + throw new TypeLoadException($"Unable to create a runtime wrapper for a WinRT object of type '{runtimeClassName}'. This type is not a projected type."); + } + vftblType = interfaceType.FindVftblType() ?? throw new TypeLoadException($"Unable to find a vtable type for the type '{runtimeClassName}'"); + } + + ParameterExpression[] parms = new[] { Expression.Parameter(typeof(IInspectable), "inspectable") }; + var createInterfaceInstanceExpression = Expression.New(interfaceType.GetConstructor(new[] { typeof(ObjectReference<>).MakeGenericType(vftblType) }), + Expression.Call(parms[0], + typeof(IInspectable).GetMethod(nameof(IInspectable.As)).MakeGenericMethod(vftblType))); + + if (classType is null) + { + return Expression.Lambda>(createInterfaceInstanceExpression, parms).Compile(); + } + + return Expression.Lambda>( + Expression.New(classType.GetConstructor(BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, new[] { interfaceType }, null), + createInterfaceInstanceExpression), + parms).Compile(); + } + } struct ComInterfaceEntry From c38b4a21d2820c66147b1f6ea7e070ab312f677d Mon Sep 17 00:00:00 2001 From: UJJWAL CHADHA Date: Wed, 16 Sep 2020 11:55:59 -0400 Subject: [PATCH 18/23] Add field access optimization for default interfaces --- WinRT.Runtime/GuidGenerator.cs | 3 +- WinRT.Runtime/IWinRTObject.net5.cs | 4 ++ WinRT.Runtime/ObjectReference.cs | 4 ++ .../SingleInterfaceOptimizedObject.net5.cs | 66 +++++++++++++++++++ cswinrt/code_writers.h | 20 ++++-- 5 files changed, 90 insertions(+), 7 deletions(-) create mode 100644 WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs diff --git a/WinRT.Runtime/GuidGenerator.cs b/WinRT.Runtime/GuidGenerator.cs index 1dbc1418a..e42c441d6 100644 --- a/WinRT.Runtime/GuidGenerator.cs +++ b/WinRT.Runtime/GuidGenerator.cs @@ -144,7 +144,8 @@ public static Guid CreateIID(Type type) var data = new byte[16 /* Number of bytes in a GUID */ + maxBytes]; Span dataSpan = data; wrt_pinterface_namespace.TryWriteBytes(dataSpan); - UTF8Encoding.UTF8.GetBytes(sig, dataSpan[16..]); + var numBytes = UTF8Encoding.UTF8.GetBytes(sig, dataSpan[16..]); + data = data[..(16 + numBytes)]; #endif using (SHA1 sha = new SHA1CryptoServiceProvider()) { diff --git a/WinRT.Runtime/IWinRTObject.net5.cs b/WinRT.Runtime/IWinRTObject.net5.cs index 2d9fcb5f6..eb0b88e37 100644 --- a/WinRT.Runtime/IWinRTObject.net5.cs +++ b/WinRT.Runtime/IWinRTObject.net5.cs @@ -42,6 +42,10 @@ bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfac } return true; } + if (vftblType.IsGenericTypeDefinition) + { + vftblType = vftblType.MakeGenericType(interfaceType.GetType().GetGenericArguments()); + } using (objRef) { IObjectReference typedObjRef = (IObjectReference)typeof(IObjectReference).GetMethod("As", Type.EmptyTypes).MakeGenericMethod(vftblType).Invoke(objRef, null); diff --git a/WinRT.Runtime/ObjectReference.cs b/WinRT.Runtime/ObjectReference.cs index 235827bf2..e59a005bd 100644 --- a/WinRT.Runtime/ObjectReference.cs +++ b/WinRT.Runtime/ObjectReference.cs @@ -74,7 +74,11 @@ public unsafe TInterface AsInterface() } } +#if NETSTANDARD2_0 return (TInterface)typeof(TInterface).GetHelperType().GetConstructor(new[] { typeof(IObjectReference) }).Invoke(new object[] { this }); +#else + return (TInterface)(object)new WinRT.IInspectable(this); +#endif } public int TryAs(out ObjectReference objRef) => TryAs(GuidGenerator.GetIID(typeof(T)), out objRef); diff --git a/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs b/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs new file mode 100644 index 000000000..b71f9d664 --- /dev/null +++ b/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +namespace WinRT +{ + public class SingleInterfaceOptimizedObject : IWinRTObject, IDynamicInterfaceCastable + { + private Type _type; + private IObjectReference _obj; + + public SingleInterfaceOptimizedObject(Type type, IObjectReference objRef) + { + this._type = type; + Type helperType = type.FindHelperType(); + var vftblType = helperType.GetNestedType("Vftbl"); + if (vftblType is null) + { + // The helper type might not have a vftbl type if it was linked away. + // The only time the Vftbl type would be linked away is when we don't actually use + // any of the methods on the interface (it was just a type cast/"is Type" check). + // In that case, we can use the IUnknownVftbl-typed ObjectReference since + // it has all of the information we'll need. + _obj = objRef; + } + if (vftblType.IsGenericTypeDefinition) + { + vftblType = vftblType.MakeGenericType(type.GetGenericArguments()); + } + this._obj = (IObjectReference)typeof(IObjectReference).GetMethod("As", Type.EmptyTypes).MakeGenericMethod(vftblType).Invoke(objRef, null); + } + + IObjectReference IWinRTObject.NativeObject => _obj; + + ConcurrentDictionary IWinRTObject.QueryInterfaceCache { get; } = new(); + + bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented) + { + if (_type.Equals(Type.GetTypeFromHandle(interfaceType))) + { + return true; + } + return (this as IWinRTObject).IsInterfaceImplemented(interfaceType, throwIfNotImplemented); + } + + RuntimeTypeHandle IDynamicInterfaceCastable.GetInterfaceImplementation(RuntimeTypeHandle interfaceType) + { + var helperType = Type.GetTypeFromHandle(interfaceType).GetHelperType(); + if (helperType.IsInterface) + return helperType.TypeHandle; + return default; + } + + IObjectReference IWinRTObject.GetObjectReferenceForType(RuntimeTypeHandle interfaceType) + { + if (_type.Equals(Type.GetTypeFromHandle(interfaceType))) + { + return _obj; + } + return (this as IWinRTObject).GetObjectReferenceForType(interfaceType); + } + + } +} diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index 25e095f90..2f99093d1 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -3,6 +3,7 @@ #include #include #include +#include namespace cswinrt { @@ -878,7 +879,8 @@ set => %.% = value; else { w.write(R"( -{typeof(%), new Lazy<%>(() => (%)(object)_default)},)", +{typeof(%), new Lazy<%>(() => (%)(object)new SingleInterfaceOptimizedObject(typeof(%), _inner))},)", + interface_name, interface_name, interface_name, interface_name); @@ -1229,7 +1231,7 @@ using IObjectReference composedRef = ObjectReference.Attach(ref c try { _inner = ComWrappersSupport.GetObjectReferenceForInterface(ptr); -_defaultLazy = new Lazy<%>(() => (%)new IInspectable(_inner)); +_defaultLazy = new Lazy<%>(() => (%)new SingleInterfaceOptimizedObject(typeof(%), _inner)); _lazyInterfaces = new Dictionary() {% }; @@ -1253,6 +1255,7 @@ MarshalInspectable.DisposeAbi(ptr); [&](writer& w) {w.write("%", params_without_objects.empty() ? " " : ", "); }, default_interface_name, default_interface_name, + default_interface_name, bind(class_type)); } } @@ -4478,8 +4481,9 @@ public static class % bool write_abi_interface(writer& w, TypeDef const& type) { - XLANG_ASSERT(get_category(type) == category::interface_type); + XLANG_ASSERT(get_category(type) == category::interface_type); auto type_name = write_type_name_temp(w, type, "%", true); + //std::cout << type_name << std::endl << std::endl << std::endl; std::set generic_methods; std::vector nongeneric_delegates; @@ -4490,12 +4494,15 @@ public static class % % internal unsafe interface % : % { -%%%%} +%%%%%} )", - // Interface abi implementation +// Interface abi implementation bind(type), type_name, bind(type, false, false), + [&](writer& w) { + w.write(distance(type.GenericParam()) > 0 ? "public static Guid PIID = Vftbl.PIID;\n\n" : ""); + }, // Vftbl bind(type, type_name, generic_methods, "", nongeneric_delegates), bind(type, generic_methods), @@ -4748,7 +4755,7 @@ return new %(objRef); % %(IObjectReference objRef)% { _inner = objRef.As(GuidGenerator.GetIID(typeof(%).GetHelperType())); -_defaultLazy = new Lazy<%>(() => (%)new global::WinRT.IInspectable(_inner)); +_defaultLazy = new Lazy<%>(() => (%)new SingleInterfaceOptimizedObject(typeof(%), _inner)); _lazyInterfaces = new Dictionary() {% }; @@ -4787,6 +4794,7 @@ private % AsInternal(InterfaceTag<%> _) => _default; default_interface_name, default_interface_name, default_interface_name, + default_interface_name, bind(type), // Equality operators type_name, From 471979e418209e825d8298354cadf4b916dc007f Mon Sep 17 00:00:00 2001 From: UJJWAL CHADHA Date: Wed, 23 Sep 2020 16:21:35 -0400 Subject: [PATCH 19/23] Added manual type mappings for IDynamicInterfaceCastable --- UnitTest/TestComponentCSharp_Tests.cs | 8 +- WinRT.Runtime/AgileReference.cs | 4 + WinRT.Runtime/ComWrappersSupport.net5.cs | 3 +- WinRT.Runtime/IWinRTObject.net5.cs | 110 +- WinRT.Runtime/Interop/IAgileReference.net5.cs | 194 ++ ...e.cs => IAgileReference.netstandard2.0.cs} | 426 ++-- .../Interop/IWeakReferenceSource.net5.cs | 178 ++ ...=> IWeakReferenceSource.netstandard2.0.cs} | 0 WinRT.Runtime/Marshalers.cs | 4 + WinRT.Runtime/Projections.cs | 8 + WinRT.Runtime/Projections/Bindable.net5.cs | 1395 ++++++++++++ ...Bindable.cs => Bindable.netstandard2.0.cs} | 121 +- .../{EventHandler.cs => EventHandler.net5.cs} | 34 +- .../EventHandler.netstandard2.0.cs | 119 + .../{Geometry.cs => Geometry.net5.cs} | 1180 +++++----- .../Projections/Geometry.netstandard2.0.cs | 591 +++++ WinRT.Runtime/Projections/ICommand.net5.cs | 324 +++ ...ICommand.cs => ICommand.netstandard2.0.cs} | 32 +- .../ICustomPropertyProvider.net5.cs | 414 ++++ ...ICustomPropertyProvider.netstandard2.0.cs} | 80 +- WinRT.Runtime/Projections/IDictionary.net5.cs | 840 ++++++++ ...onary.cs => IDictionary.netstandard2.0.cs} | 1684 +++++++-------- WinRT.Runtime/Projections/IDisposable.net5.cs | 69 + ...sable.cs => IDisposable.netstandard2.0.cs} | 16 +- WinRT.Runtime/Projections/IEnumerable.net5.cs | 638 ++++++ ...rable.cs => IEnumerable.netstandard2.0.cs} | 1286 +++++------ WinRT.Runtime/Projections/IList.net5.cs | 938 ++++++++ .../{IList.cs => IList.netstandard2.0.cs} | 1866 ++++++++-------- .../INotifyCollectionChanged.net5.cs | 96 + ...NotifyCollectionChanged.netstandard2.0.cs} | 22 +- .../INotifyPropertyChanged.net5.cs | 96 + ... INotifyPropertyChanged.netstandard2.0.cs} | 22 +- .../Projections/IPropertyValue.net5.cs | 1913 +++++++++++++++++ ...ue.cs => IPropertyValue.netstandard2.0.cs} | 600 +++--- .../Projections/IReadOnlyDictionary.net5.cs | 694 ++++++ ... => IReadOnlyDictionary.netstandard2.0.cs} | 1392 ++++++------ .../Projections/IReadOnlyList.net5.cs | 447 ++++ ...ist.cs => IReadOnlyList.netstandard2.0.cs} | 886 ++++---- .../Projections/IReferenceArray.net5.cs | 161 ++ ...y.cs => IReferenceArray.netstandard2.0.cs} | 2 +- WinRT.Runtime/Projections/IStringable.net5.cs | 54 + ...gable.cs => IStringable.netstandard2.0.cs} | 16 +- .../Projections/KeyValuePair.net5.cs | 243 +++ ...Pair.cs => KeyValuePair.netstandard2.0.cs} | 486 ++--- ... => NotifyCollectionChangedAction.net5.cs} | 2 +- ...yCollectionChangedAction.netstandard2.0.cs | 11 + ... NotifyCollectionChangedEventArgs.net5.cs} | 6 +- ...llectionChangedEventArgs.netstandard2.0.cs | 242 +++ ...tifyCollectionChangedEventHandler.net5.cs} | 32 +- ...ctionChangedEventHandler.netstandard2.0.cs | 112 + .../{Nullable.cs => Nullable.net5.cs} | 2 +- .../Projections/Nullable.netstandard2.0.cs | 150 ++ .../{Numerics.cs => Numerics.net5.cs} | 30 +- .../Projections/Numerics.netstandard2.0.cs | 56 + ...gs.cs => PropertyChangedEventArgs.net5.cs} | 6 +- ...PropertyChangedEventArgs.netstandard2.0.cs | 143 ++ ...cs => PropertyChangedEventHandler.net5.cs} | 30 +- ...pertyChangedEventHandler.netstandard2.0.cs | 113 + .../{SystemTypes.cs => SystemTypes.net5.cs} | 2 +- .../Projections/SystemTypes.netstandard2.0.cs | 136 ++ .../Projections/{Type.cs => Type.net5.cs} | 2 +- .../Projections/Type.netstandard2.0.cs | 97 + .../Projections/{Uri.cs => Uri.net5.cs} | 2 +- .../Projections/Uri.netstandard2.0.cs | 151 ++ .../SingleInterfaceOptimizedObject.net5.cs | 12 +- cswinrt/code_writers.h | 29 +- 66 files changed, 15763 insertions(+), 5295 deletions(-) create mode 100644 WinRT.Runtime/Interop/IAgileReference.net5.cs rename WinRT.Runtime/Interop/{IAgileReference.cs => IAgileReference.netstandard2.0.cs} (97%) create mode 100644 WinRT.Runtime/Interop/IWeakReferenceSource.net5.cs rename WinRT.Runtime/Interop/{IWeakReferenceSource.cs => IWeakReferenceSource.netstandard2.0.cs} (100%) create mode 100644 WinRT.Runtime/Projections/Bindable.net5.cs rename WinRT.Runtime/Projections/{Bindable.cs => Bindable.netstandard2.0.cs} (95%) rename WinRT.Runtime/Projections/{EventHandler.cs => EventHandler.net5.cs} (99%) create mode 100644 WinRT.Runtime/Projections/EventHandler.netstandard2.0.cs rename WinRT.Runtime/Projections/{Geometry.cs => Geometry.net5.cs} (96%) create mode 100644 WinRT.Runtime/Projections/Geometry.netstandard2.0.cs create mode 100644 WinRT.Runtime/Projections/ICommand.net5.cs rename WinRT.Runtime/Projections/{ICommand.cs => ICommand.netstandard2.0.cs} (95%) create mode 100644 WinRT.Runtime/Projections/ICustomPropertyProvider.net5.cs rename WinRT.Runtime/Projections/{ICustomPropertyProvider.cs => ICustomPropertyProvider.netstandard2.0.cs} (89%) create mode 100644 WinRT.Runtime/Projections/IDictionary.net5.cs rename WinRT.Runtime/Projections/{IDictionary.cs => IDictionary.netstandard2.0.cs} (97%) create mode 100644 WinRT.Runtime/Projections/IDisposable.net5.cs rename WinRT.Runtime/Projections/{IDisposable.cs => IDisposable.netstandard2.0.cs} (93%) create mode 100644 WinRT.Runtime/Projections/IEnumerable.net5.cs rename WinRT.Runtime/Projections/{IEnumerable.cs => IEnumerable.netstandard2.0.cs} (97%) create mode 100644 WinRT.Runtime/Projections/IList.net5.cs rename WinRT.Runtime/Projections/{IList.cs => IList.netstandard2.0.cs} (97%) create mode 100644 WinRT.Runtime/Projections/INotifyCollectionChanged.net5.cs rename WinRT.Runtime/Projections/{INotifyCollectionChanged.cs => INotifyCollectionChanged.netstandard2.0.cs} (83%) create mode 100644 WinRT.Runtime/Projections/INotifyPropertyChanged.net5.cs rename WinRT.Runtime/Projections/{INotifyPropertyChanged.cs => INotifyPropertyChanged.netstandard2.0.cs} (83%) create mode 100644 WinRT.Runtime/Projections/IPropertyValue.net5.cs rename WinRT.Runtime/Projections/{IPropertyValue.cs => IPropertyValue.netstandard2.0.cs} (92%) create mode 100644 WinRT.Runtime/Projections/IReadOnlyDictionary.net5.cs rename WinRT.Runtime/Projections/{IReadOnlyDictionary.cs => IReadOnlyDictionary.netstandard2.0.cs} (97%) create mode 100644 WinRT.Runtime/Projections/IReadOnlyList.net5.cs rename WinRT.Runtime/Projections/{IReadOnlyList.cs => IReadOnlyList.netstandard2.0.cs} (97%) create mode 100644 WinRT.Runtime/Projections/IReferenceArray.net5.cs rename WinRT.Runtime/Projections/{IReferenceArray.cs => IReferenceArray.netstandard2.0.cs} (99%) create mode 100644 WinRT.Runtime/Projections/IStringable.net5.cs rename WinRT.Runtime/Projections/{IStringable.cs => IStringable.netstandard2.0.cs} (90%) create mode 100644 WinRT.Runtime/Projections/KeyValuePair.net5.cs rename WinRT.Runtime/Projections/{KeyValuePair.cs => KeyValuePair.netstandard2.0.cs} (97%) rename WinRT.Runtime/Projections/{NotifyCollectionChangedAction.cs => NotifyCollectionChangedAction.net5.cs} (94%) create mode 100644 WinRT.Runtime/Projections/NotifyCollectionChangedAction.netstandard2.0.cs rename WinRT.Runtime/Projections/{NotifyCollectionChangedEventArgs.cs => NotifyCollectionChangedEventArgs.net5.cs} (99%) create mode 100644 WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.netstandard2.0.cs rename WinRT.Runtime/Projections/{NotifyCollectionChangedEventHandler.cs => NotifyCollectionChangedEventHandler.net5.cs} (99%) create mode 100644 WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.netstandard2.0.cs rename WinRT.Runtime/Projections/{Nullable.cs => Nullable.net5.cs} (99%) create mode 100644 WinRT.Runtime/Projections/Nullable.netstandard2.0.cs rename WinRT.Runtime/Projections/{Numerics.cs => Numerics.net5.cs} (98%) create mode 100644 WinRT.Runtime/Projections/Numerics.netstandard2.0.cs rename WinRT.Runtime/Projections/{PropertyChangedEventArgs.cs => PropertyChangedEventArgs.net5.cs} (99%) create mode 100644 WinRT.Runtime/Projections/PropertyChangedEventArgs.netstandard2.0.cs rename WinRT.Runtime/Projections/{PropertyChangedEventHandler.cs => PropertyChangedEventHandler.net5.cs} (99%) create mode 100644 WinRT.Runtime/Projections/PropertyChangedEventHandler.netstandard2.0.cs rename WinRT.Runtime/Projections/{SystemTypes.cs => SystemTypes.net5.cs} (99%) create mode 100644 WinRT.Runtime/Projections/SystemTypes.netstandard2.0.cs rename WinRT.Runtime/Projections/{Type.cs => Type.net5.cs} (99%) create mode 100644 WinRT.Runtime/Projections/Type.netstandard2.0.cs rename WinRT.Runtime/Projections/{Uri.cs => Uri.net5.cs} (99%) create mode 100644 WinRT.Runtime/Projections/Uri.netstandard2.0.cs diff --git a/UnitTest/TestComponentCSharp_Tests.cs b/UnitTest/TestComponentCSharp_Tests.cs index 8502eb80d..0221f6275 100644 --- a/UnitTest/TestComponentCSharp_Tests.cs +++ b/UnitTest/TestComponentCSharp_Tests.cs @@ -525,8 +525,9 @@ public void TestComposedNonBlittableStruct() Assert.True(val.bools.x); Assert.False(val.bools.y); Assert.True(val.bools.z); - } - + } + +#if NETCOREAPP2_0 [Fact] public void TestGenericCast() { @@ -534,6 +535,7 @@ public void TestGenericCast() var abiView = (ABI.System.Collections.Generic.IReadOnlyList)ints; Assert.Equal(abiView.ThisPtr, abiView.As().As.Vftbl>().ThisPtr); } +#endif [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] @@ -1493,7 +1495,7 @@ internal class ManagedType { } public void CCWOfListOfManagedType() { using var ccw = ComWrappersSupport.CreateCCWForObject(new List()); - using var qiResult = ccw.As(GuidGenerator.GetIID(typeof(ABI.System.Collections.Generic.IEnumerable))); + using var qiResult = ccw.As(GuidGenerator.GetIID(typeof(global::System.Collections.Generic.IEnumerable).GetHelperType())); } [Fact] diff --git a/WinRT.Runtime/AgileReference.cs b/WinRT.Runtime/AgileReference.cs index f2d772486..14903d310 100644 --- a/WinRT.Runtime/AgileReference.cs +++ b/WinRT.Runtime/AgileReference.cs @@ -28,7 +28,11 @@ public unsafe AgileReference(IObjectReference instance) ref iid, instance.ThisPtr, &agileReference)); +#if NET5_0 + _agileReference = (IAgileReference)new SingleInterfaceOptimizedObject(typeof(IAgileReference), ObjectReference.Attach(ref agileReference)); +#else _agileReference = ABI.WinRT.Interop.IAgileReference.FromAbi(agileReference).AsType(); +#endif } catch(TypeLoadException) { diff --git a/WinRT.Runtime/ComWrappersSupport.net5.cs b/WinRT.Runtime/ComWrappersSupport.net5.cs index 98098b86e..b84779825 100644 --- a/WinRT.Runtime/ComWrappersSupport.net5.cs +++ b/WinRT.Runtime/ComWrappersSupport.net5.cs @@ -214,7 +214,8 @@ protected override object CreateObject(IntPtr externalComObject, CreateObjectFla { // IWeakReference is IUnknown-based, so implementations of it may not (and likely won't) implement // IInspectable. As a result, we need to check for them explicitly. - return new ABI.WinRT.Interop.IWeakReference(weakRef); + + return new SingleInterfaceOptimizedObject(typeof(IWeakReference), weakRef); } // If the external COM object isn't IInspectable or IWeakReference, we can't handle it. // If we're registered globally, we want to let the runtime fall back for IUnknown and IDispatch support. diff --git a/WinRT.Runtime/IWinRTObject.net5.cs b/WinRT.Runtime/IWinRTObject.net5.cs index eb0b88e37..5b5c806b3 100644 --- a/WinRT.Runtime/IWinRTObject.net5.cs +++ b/WinRT.Runtime/IWinRTObject.net5.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Concurrent; +using System.Collections.Generic; using System.Runtime.InteropServices; using WinRT.Interop; @@ -8,12 +9,61 @@ namespace WinRT public interface IWinRTObject : IDynamicInterfaceCastable { bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented) + { + return IsInterfaceImplementedFallback(interfaceType, throwIfNotImplemented); + } + + bool IsInterfaceImplementedFallback(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented) { if (QueryInterfaceCache.ContainsKey(interfaceType)) { return true; } Type type = Type.GetTypeFromHandle(interfaceType); + + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IReadOnlyCollection<>)) + { + Type itemType = type.GetGenericArguments()[0]; + if (itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) + { + Type iReadOnlyDictionary = typeof(IReadOnlyDictionary<,>).MakeGenericType(itemType.GetGenericArguments()); + if (IsInterfaceImplemented(iReadOnlyDictionary.TypeHandle, false)) + { + return true; + } + } + Type iReadOnlyList = typeof(IReadOnlyList<>).MakeGenericType(new[] { itemType }); + if (IsInterfaceImplemented(iReadOnlyList.TypeHandle, throwIfNotImplemented)) + { + return true; + } + } + else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.ICollection<>)) + { + Type itemType = type.GetGenericArguments()[0]; + if (itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) + { + Type iDictionary = typeof(IDictionary<,>).MakeGenericType(itemType.GetGenericArguments()); + if (IsInterfaceImplemented(iDictionary.TypeHandle, false)) + { + if (QueryInterfaceCache.TryGetValue(iDictionary.TypeHandle, out var typedObjRef) && !QueryInterfaceCache.TryAdd(interfaceType, typedObjRef)) + { + typedObjRef.Dispose(); + } + return true; + } + } + Type iList = typeof(IList<>).MakeGenericType(new[] { itemType }); + if (IsInterfaceImplemented(iList.TypeHandle, throwIfNotImplemented)) + { + if (QueryInterfaceCache.TryGetValue(iList.TypeHandle, out var typedObjRef) && !QueryInterfaceCache.TryAdd(interfaceType, typedObjRef)) + { + typedObjRef.Dispose(); + } + return true; + } + } + Type helperType = type.FindHelperType(); if (helperType is null || !helperType.IsInterface) { @@ -44,7 +94,7 @@ bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfac } if (vftblType.IsGenericTypeDefinition) { - vftblType = vftblType.MakeGenericType(interfaceType.GetType().GetGenericArguments()); + vftblType = vftblType.MakeGenericType(Type.GetTypeFromHandle(interfaceType).GetGenericArguments()); } using (objRef) { @@ -59,7 +109,45 @@ bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfac RuntimeTypeHandle IDynamicInterfaceCastable.GetInterfaceImplementation(RuntimeTypeHandle interfaceType) { - var helperType = Type.GetTypeFromHandle(interfaceType).GetHelperType(); + var type = Type.GetTypeFromHandle(interfaceType); + + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IReadOnlyCollection<>)) + { + Type itemType = type.GetGenericArguments()[0]; + if (itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) + { + Type iReadOnlyDictionary = typeof(IReadOnlyDictionary<,>).MakeGenericType(itemType.GetGenericArguments()); + + if (IsInterfaceImplemented(iReadOnlyDictionary.TypeHandle, false)) + { + return GetInterfaceImplementation(iReadOnlyDictionary.TypeHandle); + } + } + Type iReadOnlyList = typeof(IReadOnlyList<>).MakeGenericType(new[] { itemType }); + if (IsInterfaceImplemented(iReadOnlyList.TypeHandle, false)) + { + return GetInterfaceImplementation(iReadOnlyList.TypeHandle); + } + } + else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.ICollection<>)) + { + Type itemType = type.GetGenericArguments()[0]; + if (itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) + { + Type iDictionary = typeof(IDictionary<,>).MakeGenericType(itemType.GetGenericArguments()); + if (IsInterfaceImplemented(iDictionary.TypeHandle, false)) + { + return GetInterfaceImplementation(iDictionary.TypeHandle); + } + } + Type iList = typeof(IList<>).MakeGenericType(new[] { itemType }); + if (IsInterfaceImplemented(iList.TypeHandle, false)) + { + return GetInterfaceImplementation(iList.TypeHandle); + } + } + + var helperType = type.GetHelperType(); if (helperType.IsInterface) return helperType.TypeHandle; return default; @@ -71,7 +159,23 @@ RuntimeTypeHandle IDynamicInterfaceCastable.GetInterfaceImplementation(RuntimeTy IObjectReference GetObjectReferenceForType(RuntimeTypeHandle type) { - return QueryInterfaceCache[type]; + return GetObjectReferenceForTypeFallback(type); + } + + IObjectReference GetObjectReferenceForTypeFallback(RuntimeTypeHandle type) + { + if (IsInterfaceImplemented(type, true)) + { + return QueryInterfaceCache[type]; + } + throw new Exception("Interface " + Type.GetTypeFromHandle(type) +" is not implemented."); + } + + ConcurrentDictionary AdditionalTypeData => new ConcurrentDictionary(); + + object GetOrCreateTypeHelperData(RuntimeTypeHandle type, Func helperDataFactory) + { + return AdditionalTypeData.GetOrAdd(type, (type) => helperDataFactory()); } } } \ No newline at end of file diff --git a/WinRT.Runtime/Interop/IAgileReference.net5.cs b/WinRT.Runtime/Interop/IAgileReference.net5.cs new file mode 100644 index 000000000..607b387cf --- /dev/null +++ b/WinRT.Runtime/Interop/IAgileReference.net5.cs @@ -0,0 +1,194 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +namespace WinRT.Interop +{ + [WindowsRuntimeType] + [Guid("C03F6A43-65A4-9818-987E-E0B810D2A6F2")] + internal interface IAgileReference + { + IObjectReference Resolve(Guid riid); + } + + [WindowsRuntimeType] + [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] + public interface IAgileObject + { + public static readonly Guid IID = Guid.Parse("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90"); + } + + [WindowsRuntimeType] + [Guid("00000146-0000-0000-C000-000000000046")] + internal interface IGlobalInterfaceTable + { + IntPtr RegisterInterfaceInGlobal(IObjectReference objRef, Guid riid); + void RevokeInterfaceFromGlobal(IntPtr cookie); + IObjectReference GetInterfaceFromGlobal(IntPtr cookie, Guid riid); + } +} + +namespace ABI.WinRT.Interop +{ + using global::WinRT; + using WinRT.Interop; + + [DynamicInterfaceCastableImplementation] + [Guid("C03F6A43-65A4-9818-987E-E0B810D2A6F2")] + internal unsafe interface IAgileReference : global::WinRT.Interop.IAgileReference + { + [Guid("C03F6A43-65A4-9818-987E-E0B810D2A6F2")] + public struct Vftbl + { + public global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; + private void* _Resolve; + public delegate* stdcall Resolve { get => (delegate* stdcall)_Resolve; set => _Resolve = value; } + + public static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + +#if NETSTANDARD2_0 + public delegate int ResolveDelegate(IntPtr thisPtr, Guid* riid, IntPtr* objectReference); + private static readonly Delegate[] DelegateCache = new Delegate[1]; +#endif + static Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, +#if NETSTANDARD2_0 + _Resolve = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ResolveDelegate(Do_Abi_Resolve)).ToPointer(), +#else + _Resolve = (delegate*)&Do_Abi_Resolve +#endif + }; + AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false); + } + +#if !NETSTANDARD2_0 + [UnmanagedCallersOnly] +#endif + private static int Do_Abi_Resolve(IntPtr thisPtr, Guid* riid, IntPtr* objectReference) + { + IObjectReference _objectReference = default; + + *objectReference = default; + + try + { + _objectReference = global::WinRT.ComWrappersSupport.FindObject(thisPtr).Resolve(*riid); + *objectReference = _objectReference?.GetRef() ?? IntPtr.Zero; + } + catch (Exception __exception__) + { + return __exception__.HResult; + } + return 0; + } + } + + public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + IObjectReference global::WinRT.Interop.IAgileReference.Resolve(Guid riid) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::WinRT.Interop.IAgileReference).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Resolve(ThisPtr, ref riid, out IntPtr ptr)); + try + { + return ComWrappersSupport.GetObjectReferenceForInterface(ptr); + } + finally + { + MarshalInspectable.DisposeAbi(ptr); + } + } + } + + [DynamicInterfaceCastableImplementation] + [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] + interface IAgileObject : global::WinRT.Interop.IAgileObject + { + [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] + public struct Vftbl + { + public global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; + + public static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, + }; + AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false); + } + } + + public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + } + + [Guid("00000146-0000-0000-C000-000000000046")] + internal unsafe class IGlobalInterfaceTable : global::WinRT.Interop.IGlobalInterfaceTable + { + [Guid("00000146-0000-0000-C000-000000000046")] + [StructLayout(LayoutKind.Sequential)] + public struct Vftbl + { + public global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; + private void* _RegisterInterfaceInGlobal; + public delegate* stdcall RegisterInterfaceInGlobal => (delegate* stdcall)_RegisterInterfaceInGlobal; + private void* _RevokeInterfaceFromGlobal; + public delegate* stdcall RevokeInterfaceFromGlobal => (delegate* stdcall)_RevokeInterfaceFromGlobal; + private void* _GetInterfaceFromGlobal; + public delegate* stdcall GetInterfaceFromGlobal => (delegate* stdcall)_GetInterfaceFromGlobal; + } + + public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + public static implicit operator IGlobalInterfaceTable(IObjectReference obj) => (obj != null) ? new IGlobalInterfaceTable(obj) : null; + public static implicit operator IGlobalInterfaceTable(ObjectReference obj) => (obj != null) ? new IGlobalInterfaceTable(obj) : null; + protected readonly ObjectReference _obj; + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + + public IGlobalInterfaceTable(IObjectReference obj) : this(obj.As()) { } + public IGlobalInterfaceTable(ObjectReference obj) + { + _obj = obj; + } + + public IntPtr RegisterInterfaceInGlobal(IObjectReference objRef, Guid riid) + { + ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RegisterInterfaceInGlobal(ThisPtr, objRef.ThisPtr, ref riid, out IntPtr cookie)); + return cookie; + + } + + public void RevokeInterfaceFromGlobal(IntPtr cookie) + { + ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RevokeInterfaceFromGlobal(ThisPtr, cookie)); + } + + public IObjectReference GetInterfaceFromGlobal(IntPtr cookie, Guid riid) + { + ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetInterfaceFromGlobal(ThisPtr, cookie, ref riid, out IntPtr ptr)); + try + { + return ComWrappersSupport.GetObjectReferenceForInterface(ptr); + } + finally + { + MarshalInspectable.DisposeAbi(ptr); + } + } + } +} diff --git a/WinRT.Runtime/Interop/IAgileReference.cs b/WinRT.Runtime/Interop/IAgileReference.netstandard2.0.cs similarity index 97% rename from WinRT.Runtime/Interop/IAgileReference.cs rename to WinRT.Runtime/Interop/IAgileReference.netstandard2.0.cs index fcc24bf87..686c56821 100644 --- a/WinRT.Runtime/Interop/IAgileReference.cs +++ b/WinRT.Runtime/Interop/IAgileReference.netstandard2.0.cs @@ -1,213 +1,213 @@ -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; - -namespace WinRT.Interop -{ - [WindowsRuntimeType] - [Guid("C03F6A43-65A4-9818-987E-E0B810D2A6F2")] - internal interface IAgileReference - { - IObjectReference Resolve(Guid riid); - } - - [WindowsRuntimeType] - [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] - public interface IAgileObject - { - } - - [WindowsRuntimeType] - [Guid("00000146-0000-0000-C000-000000000046")] - internal interface IGlobalInterfaceTable - { - IntPtr RegisterInterfaceInGlobal(IObjectReference objRef, Guid riid); - void RevokeInterfaceFromGlobal(IntPtr cookie); - IObjectReference GetInterfaceFromGlobal(IntPtr cookie, Guid riid); - } -} - -namespace ABI.WinRT.Interop -{ - using global::WinRT; - using WinRT.Interop; - - [Guid("C03F6A43-65A4-9818-987E-E0B810D2A6F2")] - internal unsafe class IAgileReference : global::WinRT.Interop.IAgileReference - { - [Guid("C03F6A43-65A4-9818-987E-E0B810D2A6F2")] - public struct Vftbl - { - public global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; - private void* _Resolve; - public delegate* stdcall Resolve { get => (delegate* stdcall)_Resolve; set => _Resolve = value; } - - public static readonly Vftbl AbiToProjectionVftable; - public static readonly IntPtr AbiToProjectionVftablePtr; - -#if NETSTANDARD2_0 - public delegate int ResolveDelegate(IntPtr thisPtr, Guid* riid, IntPtr* objectReference); - private static readonly Delegate[] DelegateCache = new Delegate[1]; -#endif - static Vftbl() - { - AbiToProjectionVftable = new Vftbl - { - IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, -#if NETSTANDARD2_0 - _Resolve = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ResolveDelegate(Do_Abi_Resolve)).ToPointer(), -#else - _Resolve = (delegate*)&Do_Abi_Resolve -#endif - }; - AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf()); - Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false); - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif - private static int Do_Abi_Resolve(IntPtr thisPtr, Guid* riid, IntPtr* objectReference) - { - IObjectReference _objectReference = default; - - *objectReference = default; - - try - { - _objectReference = global::WinRT.ComWrappersSupport.FindObject(thisPtr).Resolve(*riid); - *objectReference = _objectReference?.GetRef() ?? IntPtr.Zero; - } - catch (Exception __exception__) - { - return __exception__.HResult; - } - return 0; - } - } - - public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); - - public static implicit operator IAgileReference(IObjectReference obj) => (obj != null) ? new IAgileReference(obj) : null; - public static implicit operator IAgileReference(ObjectReference obj) => (obj != null) ? new IAgileReference(obj) : null; - protected readonly ObjectReference _obj; - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - - public IAgileReference(IObjectReference obj) : this(obj.As()) { } - public IAgileReference(ObjectReference obj) - { - _obj = obj; - } - - public IObjectReference Resolve(Guid riid) - { - ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Resolve(ThisPtr, ref riid, out IntPtr ptr)); - try - { - return ComWrappersSupport.GetObjectReferenceForInterface(ptr); - } - finally - { - MarshalInspectable.DisposeAbi(ptr); - } - } - } - - [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] - public class IAgileObject : global::WinRT.Interop.IAgileObject - { - [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] - public struct Vftbl - { - public global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; - - public static readonly Vftbl AbiToProjectionVftable; - public static readonly IntPtr AbiToProjectionVftablePtr; - - static Vftbl() - { - AbiToProjectionVftable = new Vftbl - { - IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, - }; - AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf()); - Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false); - } - } - - public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); - - public static implicit operator IAgileObject(IObjectReference obj) => (obj != null) ? new IAgileObject(obj) : null; - public static implicit operator IAgileObject(ObjectReference obj) => (obj != null) ? new IAgileObject(obj) : null; - protected readonly ObjectReference _obj; - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - - public IAgileObject(IObjectReference obj) : this(obj.As()) { } - public IAgileObject(ObjectReference obj) - { - _obj = obj; - } - } - - [Guid("00000146-0000-0000-C000-000000000046")] - internal unsafe class IGlobalInterfaceTable : global::WinRT.Interop.IGlobalInterfaceTable - { - [Guid("00000146-0000-0000-C000-000000000046")] - [StructLayout(LayoutKind.Sequential)] - public struct Vftbl - { - public global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; - private void* _RegisterInterfaceInGlobal; - public delegate* stdcall RegisterInterfaceInGlobal => (delegate* stdcall)_RegisterInterfaceInGlobal; - private void* _RevokeInterfaceFromGlobal; - public delegate* stdcall RevokeInterfaceFromGlobal => (delegate* stdcall)_RevokeInterfaceFromGlobal; - private void* _GetInterfaceFromGlobal; - public delegate* stdcall GetInterfaceFromGlobal => (delegate* stdcall)_GetInterfaceFromGlobal; - } - - public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); - - public static implicit operator IGlobalInterfaceTable(IObjectReference obj) => (obj != null) ? new IGlobalInterfaceTable(obj) : null; - public static implicit operator IGlobalInterfaceTable(ObjectReference obj) => (obj != null) ? new IGlobalInterfaceTable(obj) : null; - protected readonly ObjectReference _obj; - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - - public IGlobalInterfaceTable(IObjectReference obj) : this(obj.As()) { } - public IGlobalInterfaceTable(ObjectReference obj) - { - _obj = obj; - } - - public IntPtr RegisterInterfaceInGlobal(IObjectReference objRef, Guid riid) - { - ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RegisterInterfaceInGlobal(ThisPtr, objRef.ThisPtr, ref riid, out IntPtr cookie)); - return cookie; - - } - - public void RevokeInterfaceFromGlobal(IntPtr cookie) - { - ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RevokeInterfaceFromGlobal(ThisPtr, cookie)); - } - - public IObjectReference GetInterfaceFromGlobal(IntPtr cookie, Guid riid) - { - ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetInterfaceFromGlobal(ThisPtr, cookie, ref riid, out IntPtr ptr)); - try - { - return ComWrappersSupport.GetObjectReferenceForInterface(ptr); - } - finally - { - MarshalInspectable.DisposeAbi(ptr); - } - } - } -} +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +namespace WinRT.Interop +{ + [WindowsRuntimeType] + [Guid("C03F6A43-65A4-9818-987E-E0B810D2A6F2")] + internal interface IAgileReference + { + IObjectReference Resolve(Guid riid); + } + + [WindowsRuntimeType] + [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] + public interface IAgileObject + { + } + + [WindowsRuntimeType] + [Guid("00000146-0000-0000-C000-000000000046")] + internal interface IGlobalInterfaceTable + { + IntPtr RegisterInterfaceInGlobal(IObjectReference objRef, Guid riid); + void RevokeInterfaceFromGlobal(IntPtr cookie); + IObjectReference GetInterfaceFromGlobal(IntPtr cookie, Guid riid); + } +} + +namespace ABI.WinRT.Interop +{ + using global::WinRT; + using WinRT.Interop; + + [Guid("C03F6A43-65A4-9818-987E-E0B810D2A6F2")] + internal unsafe class IAgileReference : global::WinRT.Interop.IAgileReference + { + [Guid("C03F6A43-65A4-9818-987E-E0B810D2A6F2")] + public struct Vftbl + { + public global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; + private void* _Resolve; + public delegate* stdcall Resolve { get => (delegate* stdcall)_Resolve; set => _Resolve = value; } + + public static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + +#if NETSTANDARD2_0 + public delegate int ResolveDelegate(IntPtr thisPtr, Guid* riid, IntPtr* objectReference); + private static readonly Delegate[] DelegateCache = new Delegate[1]; +#endif + static Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, +#if NETSTANDARD2_0 + _Resolve = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ResolveDelegate(Do_Abi_Resolve)).ToPointer(), +#else + _Resolve = (delegate*)&Do_Abi_Resolve +#endif + }; + AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false); + } + +#if !NETSTANDARD2_0 + [UnmanagedCallersOnly] +#endif + private static int Do_Abi_Resolve(IntPtr thisPtr, Guid* riid, IntPtr* objectReference) + { + IObjectReference _objectReference = default; + + *objectReference = default; + + try + { + _objectReference = global::WinRT.ComWrappersSupport.FindObject(thisPtr).Resolve(*riid); + *objectReference = _objectReference?.GetRef() ?? IntPtr.Zero; + } + catch (Exception __exception__) + { + return __exception__.HResult; + } + return 0; + } + } + + public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + public static implicit operator IAgileReference(IObjectReference obj) => (obj != null) ? new IAgileReference(obj) : null; + public static implicit operator IAgileReference(ObjectReference obj) => (obj != null) ? new IAgileReference(obj) : null; + protected readonly ObjectReference _obj; + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + + public IAgileReference(IObjectReference obj) : this(obj.As()) { } + public IAgileReference(ObjectReference obj) + { + _obj = obj; + } + + public IObjectReference Resolve(Guid riid) + { + ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Resolve(ThisPtr, ref riid, out IntPtr ptr)); + try + { + return ComWrappersSupport.GetObjectReferenceForInterface(ptr); + } + finally + { + MarshalInspectable.DisposeAbi(ptr); + } + } + } + + [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] + public class IAgileObject : global::WinRT.Interop.IAgileObject + { + [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] + public struct Vftbl + { + public global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; + + public static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, + }; + AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false); + } + } + + public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + public static implicit operator IAgileObject(IObjectReference obj) => (obj != null) ? new IAgileObject(obj) : null; + public static implicit operator IAgileObject(ObjectReference obj) => (obj != null) ? new IAgileObject(obj) : null; + protected readonly ObjectReference _obj; + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + + public IAgileObject(IObjectReference obj) : this(obj.As()) { } + public IAgileObject(ObjectReference obj) + { + _obj = obj; + } + } + + [Guid("00000146-0000-0000-C000-000000000046")] + internal unsafe class IGlobalInterfaceTable : global::WinRT.Interop.IGlobalInterfaceTable + { + [Guid("00000146-0000-0000-C000-000000000046")] + [StructLayout(LayoutKind.Sequential)] + public struct Vftbl + { + public global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; + private void* _RegisterInterfaceInGlobal; + public delegate* stdcall RegisterInterfaceInGlobal => (delegate* stdcall)_RegisterInterfaceInGlobal; + private void* _RevokeInterfaceFromGlobal; + public delegate* stdcall RevokeInterfaceFromGlobal => (delegate* stdcall)_RevokeInterfaceFromGlobal; + private void* _GetInterfaceFromGlobal; + public delegate* stdcall GetInterfaceFromGlobal => (delegate* stdcall)_GetInterfaceFromGlobal; + } + + public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + public static implicit operator IGlobalInterfaceTable(IObjectReference obj) => (obj != null) ? new IGlobalInterfaceTable(obj) : null; + public static implicit operator IGlobalInterfaceTable(ObjectReference obj) => (obj != null) ? new IGlobalInterfaceTable(obj) : null; + protected readonly ObjectReference _obj; + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + + public IGlobalInterfaceTable(IObjectReference obj) : this(obj.As()) { } + public IGlobalInterfaceTable(ObjectReference obj) + { + _obj = obj; + } + + public IntPtr RegisterInterfaceInGlobal(IObjectReference objRef, Guid riid) + { + ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RegisterInterfaceInGlobal(ThisPtr, objRef.ThisPtr, ref riid, out IntPtr cookie)); + return cookie; + + } + + public void RevokeInterfaceFromGlobal(IntPtr cookie) + { + ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RevokeInterfaceFromGlobal(ThisPtr, cookie)); + } + + public IObjectReference GetInterfaceFromGlobal(IntPtr cookie, Guid riid) + { + ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetInterfaceFromGlobal(ThisPtr, cookie, ref riid, out IntPtr ptr)); + try + { + return ComWrappersSupport.GetObjectReferenceForInterface(ptr); + } + finally + { + MarshalInspectable.DisposeAbi(ptr); + } + } + } +} diff --git a/WinRT.Runtime/Interop/IWeakReferenceSource.net5.cs b/WinRT.Runtime/Interop/IWeakReferenceSource.net5.cs new file mode 100644 index 000000000..2ad33ca0c --- /dev/null +++ b/WinRT.Runtime/Interop/IWeakReferenceSource.net5.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +namespace WinRT.Interop +{ + [WindowsRuntimeType] + [Guid("00000038-0000-0000-C000-000000000046")] + internal interface IWeakReferenceSource + { + IWeakReference GetWeakReference(); + } + + [WindowsRuntimeType] + [Guid("00000037-0000-0000-C000-000000000046")] + internal interface IWeakReference + { + IObjectReference Resolve(Guid riid); + } + + internal class ManagedWeakReference : IWeakReference + { + private WeakReference _ref; + public ManagedWeakReference(object obj) + { + _ref = new WeakReference(obj); + } + + public IObjectReference Resolve(Guid riid) + { + if (!_ref.TryGetTarget(out object target)) + { + return null; + } + + using (IObjectReference objReference = ComWrappersSupport.CreateCCWForObject(target)) + { + return objReference.As(riid); + } + } + } +} + + +namespace ABI.WinRT.Interop +{ + using global::WinRT; + using WinRT.Interop; + + [DynamicInterfaceCastableImplementation] + [Guid("00000038-0000-0000-C000-000000000046")] + internal unsafe interface IWeakReferenceSource : global::WinRT.Interop.IWeakReferenceSource + { + [Guid("00000038-0000-0000-C000-000000000046")] + public struct Vftbl + { + public global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; + private void* _GetWeakReference; + public delegate* stdcall GetWeakReference { get => (delegate* stdcall)_GetWeakReference; set => _GetWeakReference = value; } + + public static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, + + _GetWeakReference = (delegate*)&Do_Abi_GetWeakReference + + }; + AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false); + } + + + [UnmanagedCallersOnly] + + private static int Do_Abi_GetWeakReference(IntPtr thisPtr, IntPtr* weakReference) + { + *weakReference = default; + + try + { + *weakReference = ComWrappersSupport.CreateCCWForObject(new global::WinRT.Interop.ManagedWeakReference(ComWrappersSupport.FindObject(thisPtr))).As().GetRef(); + } + catch (Exception __exception__) + { + return __exception__.HResult; + } + return 0; + } + } + + public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + global::WinRT.Interop.IWeakReference global::WinRT.Interop.IWeakReferenceSource.GetWeakReference() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::WinRT.Interop.IWeakReferenceSource).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + IntPtr objRef = IntPtr.Zero; + try + { + ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetWeakReference(ThisPtr, out objRef)); + return MarshalInterface.FromAbi(objRef); + } + finally + { + MarshalInspectable.DisposeAbi(objRef); + } + } + } + + [DynamicInterfaceCastableImplementation] + [Guid("00000037-0000-0000-C000-000000000046")] + internal unsafe interface IWeakReference : global::WinRT.Interop.IWeakReference + { + [Guid("00000037-0000-0000-C000-000000000046")] + public struct Vftbl + { + public global::WinRT.Interop.IUnknownVftbl IUnknownVftbl; + private void* _Resolve; + public delegate* stdcall Resolve { get => (delegate* stdcall)_Resolve; set => _Resolve = value; } + + public static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + + static Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, + + _Resolve = (delegate*)&Do_Abi_Resolve + + }; + AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false); + } + + + [UnmanagedCallersOnly] + + private static int Do_Abi_Resolve(IntPtr thisPtr, Guid* riid, IntPtr* objectReference) + { + IObjectReference _objectReference = default; + + *objectReference = default; + + try + { + _objectReference = global::WinRT.ComWrappersSupport.FindObject(thisPtr).Resolve(*riid); + *objectReference = _objectReference?.GetRef() ?? IntPtr.Zero; + } + catch (Exception __exception__) + { + return __exception__.HResult; + } + return 0; + } + } + + public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + IObjectReference global::WinRT.Interop.IWeakReference.Resolve(Guid riid) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::WinRT.Interop.IWeakReference).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Resolve(ThisPtr, ref riid, out IntPtr objRef)); + return ComWrappersSupport.GetObjectReferenceForInterface(objRef); + } + } +} diff --git a/WinRT.Runtime/Interop/IWeakReferenceSource.cs b/WinRT.Runtime/Interop/IWeakReferenceSource.netstandard2.0.cs similarity index 100% rename from WinRT.Runtime/Interop/IWeakReferenceSource.cs rename to WinRT.Runtime/Interop/IWeakReferenceSource.netstandard2.0.cs diff --git a/WinRT.Runtime/Marshalers.cs b/WinRT.Runtime/Marshalers.cs index cfa0b3772..e992b8856 100644 --- a/WinRT.Runtime/Marshalers.cs +++ b/WinRT.Runtime/Marshalers.cs @@ -816,6 +816,9 @@ public static T FromAbi(IntPtr ptr) { return obj; } +#if !NETSTANDARD2_0 + return (T)(object)IInspectable.FromAbi(ptr); +#else // If the metadata type doesn't implement the interface, then create a tear-off RCW. // TODO: Uniqueness of tear-offs? if (_FromAbi == null) @@ -823,6 +826,7 @@ public static T FromAbi(IntPtr ptr) _FromAbi = BindFromAbi(); } return _FromAbi(ptr); +#endif } public static IObjectReference CreateMarshaler(T value) diff --git a/WinRT.Runtime/Projections.cs b/WinRT.Runtime/Projections.cs index bc2eb9af0..5cdb51706 100644 --- a/WinRT.Runtime/Projections.cs +++ b/WinRT.Runtime/Projections.cs @@ -7,6 +7,7 @@ using System.Reflection; using System.Threading; using System.Windows.Input; +using Windows.Foundation.Collections; namespace WinRT { @@ -59,6 +60,13 @@ static Projections() RegisterCustomAbiTypeMappingNoLock(typeof(Vector2), typeof(ABI.System.Numerics.Vector2), "Windows.Foundation.Numerics.Vector2"); RegisterCustomAbiTypeMappingNoLock(typeof(Vector3), typeof(ABI.System.Numerics.Vector3), "Windows.Foundation.Numerics.Vector3"); RegisterCustomAbiTypeMappingNoLock(typeof(Vector4), typeof(ABI.System.Numerics.Vector4), "Windows.Foundation.Numerics.Vector4"); + + CustomTypeToHelperTypeMappings.Add(typeof(IMap<,>), typeof(ABI.System.Collections.Generic.IDictionary<,>)); + CustomTypeToHelperTypeMappings.Add(typeof(IVector<>), typeof(ABI.System.Collections.Generic.IList<>)); + CustomTypeToHelperTypeMappings.Add(typeof(IMapView<,>), typeof(ABI.System.Collections.Generic.IReadOnlyDictionary<,>)); + CustomTypeToHelperTypeMappings.Add(typeof(IVectorView<>), typeof(ABI.System.Collections.Generic.IReadOnlyList<>)); + CustomTypeToHelperTypeMappings.Add(typeof(global::Microsoft.UI.Xaml.Interop.IBindableVector), typeof(ABI.System.Collections.IList)); + } public static void RegisterCustomAbiTypeMapping(Type publicType, Type abiType, string winrtTypeName, bool isRuntimeClass = false) diff --git a/WinRT.Runtime/Projections/Bindable.net5.cs b/WinRT.Runtime/Projections/Bindable.net5.cs new file mode 100644 index 000000000..3da27dd6b --- /dev/null +++ b/WinRT.Runtime/Projections/Bindable.net5.cs @@ -0,0 +1,1395 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using Microsoft.UI.Xaml.Interop; +using WinRT; +using WinRT.Interop; + + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Microsoft.UI.Xaml.Interop +{ + [global::WinRT.WindowsRuntimeType] + [Guid("036D2C08-DF29-41AF-8AA2-D774BE62BA6F")] + internal interface IBindableIterable + { + IBindableIterator First(); + } + [global::WinRT.WindowsRuntimeType] + [Guid("6A1D6C07-076D-49F2-8314-F52C9C9A8331")] + internal interface IBindableIterator + { + bool MoveNext(); + object Current { get; } + bool HasCurrent { get; } + } + [global::WinRT.WindowsRuntimeType] + [Guid("393DE7DE-6FD0-4C0D-BB71-47244A113E93")] + internal interface IBindableVector : IEnumerable + { + object GetAt(uint index); + IBindableVectorView GetView(); + bool IndexOf(object value, out uint index); + void SetAt(uint index, object value); + void InsertAt(uint index, object value); + void RemoveAt(uint index); + void Append(object value); + void RemoveAtEnd(); + void Clear(); + uint Size { get; } + } + [global::WinRT.WindowsRuntimeType] + [Guid("346DD6E7-976E-4BC3-815D-ECE243BC0F33")] + internal interface IBindableVectorView : IEnumerable + { + object GetAt(uint index); + bool IndexOf(object value, out uint index); + uint Size { get; } + } +} + +namespace ABI.Microsoft.UI.Xaml.Interop +{ + [DynamicInterfaceCastableImplementation] + [Guid("036D2C08-DF29-41AF-8AA2-D774BE62BA6F")] + internal unsafe interface IBindableIterable : global::Microsoft.UI.Xaml.Interop.IBindableIterable, ABI.System.Collections.IEnumerable + { + + } + + [DynamicInterfaceCastableImplementation] + [Guid("6A1D6C07-076D-49F2-8314-F52C9C9A8331")] + internal unsafe interface IBindableIterator : global::Microsoft.UI.Xaml.Interop.IBindableIterator + { + [Guid("6A1D6C07-076D-49F2-8314-F52C9C9A8331")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + private void* _get_Current_0; + public delegate* stdcall get_Current_0 { get => (delegate* stdcall)_get_Current_0; set => _get_Current_0 = value; } + private void* _get_HasCurrent_1; + public delegate* stdcall get_HasCurrent_1 { get => (delegate* stdcall)_get_HasCurrent_1; set => _get_HasCurrent_1 = value; } + private void* _MoveNext_2; + public delegate* stdcall MoveNext_2 { get => (delegate* stdcall)_MoveNext_2; set => _MoveNext_2 = value; } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + _get_Current_0 = (delegate*)&Do_Abi_get_Current_0, + _get_HasCurrent_1 = (delegate*)&Do_Abi_get_HasCurrent_1, + _MoveNext_2 = (delegate*)&Do_Abi_MoveNext_2 + + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 3); + Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_MoveNext_2(IntPtr thisPtr, byte* result) + { + bool __result = default; + *result = default; + try + { + __result = global::WinRT.ComWrappersSupport.FindObject(thisPtr).MoveNext(); + *result = (byte)(__result ? 1 : 0); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_get_Current_0(IntPtr thisPtr, IntPtr* value) + { + object __value = default; + *value = default; + try + { + __value = global::WinRT.ComWrappersSupport.FindObject(thisPtr).Current; + *value = MarshalInspectable.FromManaged(__value); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_get_HasCurrent_1(IntPtr thisPtr, byte* value) + { + bool __value = default; + *value = default; + try + { + __value = global::WinRT.ComWrappersSupport.FindObject(thisPtr).HasCurrent; + *value = (byte)(__value ? 1 : 0); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + internal static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + unsafe bool global::Microsoft.UI.Xaml.Interop.IBindableIterator.MoveNext() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Microsoft.UI.Xaml.Interop.IBindableIterator).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + byte __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.MoveNext_2(ThisPtr, &__retval)); + return __retval != 0; + } + + unsafe object global::Microsoft.UI.Xaml.Interop.IBindableIterator.Current + { + get + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Microsoft.UI.Xaml.Interop.IBindableIterator).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Current_0(ThisPtr, &__retval)); + return MarshalInspectable.FromAbi(__retval); + } + finally + { + MarshalInspectable.DisposeAbi(__retval); + } + } + } + + unsafe bool global::Microsoft.UI.Xaml.Interop.IBindableIterator.HasCurrent + { + get + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Microsoft.UI.Xaml.Interop.IBindableIterator).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + byte __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_HasCurrent_1(ThisPtr, &__retval)); + return __retval != 0; + } + } + + } + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + internal static class IBindableIterator_Delegates + { + public unsafe delegate int get_Current_0(IntPtr thisPtr, IntPtr* result); + public unsafe delegate int get_HasCurrent_1(IntPtr thisPtr, byte* result); + public unsafe delegate int MoveNext_2(IntPtr thisPtr, byte* result); + } + + [DynamicInterfaceCastableImplementation] + [Guid("346DD6E7-976E-4BC3-815D-ECE243BC0F33")] + internal unsafe interface IBindableVectorView : global::Microsoft.UI.Xaml.Interop.IBindableVectorView + { + [Guid("346DD6E7-976E-4BC3-815D-ECE243BC0F33")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + private void* _GetAt_0; + public delegate* stdcall GetAt_0 { get => (delegate* stdcall)_GetAt_0; set => _GetAt_0 = value; } + private void* _get_Size_1; + public delegate* stdcall get_Size_1 { get => (delegate* stdcall)_get_Size_1; set => _get_Size_1 = value; } + private void* _IndexOf_2; + public delegate* stdcall IndexOf_2 { get => (delegate* stdcall)_IndexOf_2; set => _IndexOf_2 = value; } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + _GetAt_0 = (delegate*)&Do_Abi_GetAt_0, + _get_Size_1 = (delegate*)&Do_Abi_get_Size_1, + _IndexOf_2 = (delegate*)&Do_Abi_IndexOf_2 + + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 3); + Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetAt_0(IntPtr thisPtr, uint index, IntPtr* result) + { + object __result = default; + + try + { + __result = global::WinRT.ComWrappersSupport.FindObject(thisPtr).GetAt(index); + *result = MarshalInspectable.FromManaged(__result); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_IndexOf_2(IntPtr thisPtr, IntPtr value, uint* index, byte* returnValue) + { + bool __returnValue = default; + + *index = default; + *returnValue = default; + uint __index = default; + + try + { + __returnValue = global::WinRT.ComWrappersSupport.FindObject(thisPtr).IndexOf(MarshalInspectable.FromAbi(value), out __index); + *index = __index; + *returnValue = (byte)(__returnValue ? 1 : 0); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, uint* value) + { + uint __value = default; + + *value = default; + + try + { + __value = global::WinRT.ComWrappersSupport.FindObject(thisPtr).Size; + *value = __value; + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + internal static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + private static global::System.Runtime.CompilerServices.ConditionalWeakTable _helperTable = + new global::System.Runtime.CompilerServices.ConditionalWeakTable(); + + unsafe object global::Microsoft.UI.Xaml.Interop.IBindableVectorView.GetAt(uint index) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Microsoft.UI.Xaml.Interop.IBindableIterator).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetAt_0(ThisPtr, index, &__retval)); + return MarshalInspectable.FromAbi(__retval); + } + finally + { + MarshalInspectable.DisposeAbi(__retval); + } + } + + unsafe bool global::Microsoft.UI.Xaml.Interop.IBindableVectorView.IndexOf(object value, out uint index) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Microsoft.UI.Xaml.Interop.IBindableIterator).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IObjectReference __value = default; + uint __index = default; + byte __retval = default; + try + { + __value = MarshalInspectable.CreateMarshaler(value); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.IndexOf_2(ThisPtr, MarshalInspectable.GetAbi(__value), &__index, &__retval)); + index = __index; + return __retval != 0; + } + finally + { + MarshalInspectable.DisposeMarshaler(__value); + } + } + + unsafe uint global::Microsoft.UI.Xaml.Interop.IBindableVectorView.Size + { + get + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Microsoft.UI.Xaml.Interop.IBindableIterator).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + uint __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, &__retval)); + return __retval; + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return _helperTable.GetValue((IWinRTObject)this, + (enumerable) => new ABI.System.Collections.IEnumerable.FromAbiHelper((global::System.Collections.IEnumerable)(IWinRTObject)enumerable) + ).GetEnumerator(); + } + } + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + internal static class IBindableVectorView_Delegates + { + public unsafe delegate int GetAt_0(IntPtr thisPtr, uint index, IntPtr* result); + public unsafe delegate int get_Size_1(IntPtr thisPtr, uint* result); + public unsafe delegate int IndexOf_2(IntPtr thisPtr, IntPtr value, uint* index, byte* returnValue); + } +} + +namespace ABI.System.Collections +{ + using global::System; + using global::System.Runtime.CompilerServices; + using global::Microsoft.UI.Xaml.Interop; + + [DynamicInterfaceCastableImplementation] + [Guid("036D2C08-DF29-41AF-8AA2-D774BE62BA6F")] + internal unsafe interface IEnumerable : global::System.Collections.IEnumerable, global::Microsoft.UI.Xaml.Interop.IBindableIterable + { + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IEnumerable)); + + public class FromAbiHelper : global::System.Collections.IEnumerable + { + private readonly global::System.Collections.IEnumerable _iterable; + + public FromAbiHelper(global::System.Collections.IEnumerable iterable) + { + _iterable = iterable; + } + + public global::System.Collections.IEnumerator GetEnumerator() => + new Generic.IEnumerator.FromAbiHelper(new NonGenericToGenericIterator(((global::Microsoft.UI.Xaml.Interop.IBindableIterable)(IWinRTObject)_iterable).First())); + + private sealed class NonGenericToGenericIterator : global::Windows.Foundation.Collections.IIterator + { + private readonly IBindableIterator iterator; + + public NonGenericToGenericIterator(IBindableIterator iterator) => this.iterator = iterator; + + public object _Current => iterator.Current; + public bool HasCurrent => iterator.HasCurrent; + public bool _MoveNext() { return iterator.MoveNext(); } + public uint GetMany(ref object[] items) => throw new NotSupportedException(); + } + } + + public class ToAbiHelper : IBindableIterable + { + private readonly IEnumerable m_enumerable; + + internal ToAbiHelper(IEnumerable enumerable) => m_enumerable = enumerable; + + IBindableIterator IBindableIterable.First() => MakeBindableIterator(m_enumerable.GetEnumerator()); + + internal static IBindableIterator MakeBindableIterator(IEnumerator enumerator) => + new Generic.IEnumerator.ToAbiHelper(new NonGenericToGenericEnumerator(enumerator)); + + private sealed class NonGenericToGenericEnumerator : IEnumerator + { + private readonly IEnumerator enumerator; + + public NonGenericToGenericEnumerator(IEnumerator enumerator) => this.enumerator = enumerator; + + public object Current => enumerator.Current; + public bool MoveNext() { return enumerator.MoveNext(); } + public void Reset() { enumerator.Reset(); } + public void Dispose() { } + } + } + + [Guid("036D2C08-DF29-41AF-8AA2-D774BE62BA6F")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + private void* _First_0; + public delegate* stdcall First_0 { get => (delegate* stdcall)_First_0; set => _First_0 = value; } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + _First_0 = (delegate* )&Do_Abi_First_0 + + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 1); + Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_First_0(IntPtr thisPtr, IntPtr* result) + { + *result = default; + try + { + var __this = global::WinRT.ComWrappersSupport.FindObject(thisPtr); + var iterator = ToAbiHelper.MakeBindableIterator(__this.GetEnumerator()); + *result = MarshalInterface.FromManaged(iterator); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + internal static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + return ObjectReference.FromAbi(thisPtr); + } + + private static FromAbiHelper _AbiHelper(IWinRTObject _this) + { + return (FromAbiHelper)_this.GetOrCreateTypeHelperData(typeof(global::System.Collections.IEnumerable).TypeHandle, + () => new FromAbiHelper((global::System.Collections.IEnumerable)_this)); + } + + unsafe global::Microsoft.UI.Xaml.Interop.IBindableIterator global::Microsoft.UI.Xaml.Interop.IBindableIterable.First() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.IEnumerable).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.First_0(ThisPtr, &__retval)); + return MarshalInterface.FromAbi(__retval); + } + finally + { + MarshalInterface.DisposeAbi(__retval); + } + } + + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() + { + return _AbiHelper((IWinRTObject)this).GetEnumerator(); + } + } + + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static class IEnumerable_Delegates + { + public unsafe delegate int First_0(IntPtr thisPtr, IntPtr* result); + } + + [DynamicInterfaceCastableImplementation] + [Guid("393DE7DE-6FD0-4C0D-BB71-47244A113E93")] + unsafe interface IList : global::System.Collections.IList, global::Microsoft.UI.Xaml.Interop.IBindableVector + { + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IList)); + + public class FromAbiHelper : global::System.Collections.IList + { + private readonly global::Microsoft.UI.Xaml.Interop.IBindableVector _vector; + + public FromAbiHelper(global::Microsoft.UI.Xaml.Interop.IBindableVector vector) + { + _vector = vector; + } + + public bool IsSynchronized => false; + + public object SyncRoot { get => this; } + + public int Count + { + get + { + uint size = _vector.Size; + if (((uint)int.MaxValue) < size) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); + } + + return (int)size; + } + } + + public void CopyTo(Array array, int arrayIndex) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + + // ICollection expects the destination array to be single-dimensional. + if (array.Rank != 1) + throw new ArgumentException(ErrorStrings.Arg_RankMultiDimNotSupported); + + int destLB = array.GetLowerBound(0); + int srcLen = Count; + int destLen = array.GetLength(0); + + if (arrayIndex < destLB) + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); + + // Does the dimension in question have sufficient space to copy the expected number of entries? + // We perform this check before valid index check to ensure the exception message is in sync with + // the following snippet that uses regular framework code: + // + // ArrayList list = new ArrayList(); + // list.Add(1); + // Array items = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { -1 }); + // list.CopyTo(items, 0); + + if (srcLen > (destLen - (arrayIndex - destLB))) + throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); + + if (arrayIndex - destLB > destLen) + throw new ArgumentException(ErrorStrings.Argument_IndexOutOfArrayBounds); + + // We need to verify the index as we; + for (uint i = 0; i < srcLen; i++) + { + array.SetValue(_vector.GetAt(i), i + arrayIndex); + } + } + + public object this[int index] + { + get => Indexer_Get(index); + set => Indexer_Set(index, value); + } + + internal object Indexer_Get(int index) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + + return GetAt(_vector, (uint)index); + } + + internal void Indexer_Set(int index, object value) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + + SetAt(_vector, (uint)index, value); + } + + public int Add(object value) + { + _vector.Append(value); + + uint size = _vector.Size; + if (((uint)int.MaxValue) < size) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); + } + + return (int)(size - 1); + } + + public bool Contains(object item) + { + return _vector.IndexOf(item, out _); + } + + public void Clear() + { + _vector.Clear(); + } + + public bool IsFixedSize { get => false; } + + public bool IsReadOnly { get => false; } + + public int IndexOf(object item) + { + uint index; + bool exists = _vector.IndexOf(item, out index); + + if (!exists) + return -1; + + if (((uint)int.MaxValue) < index) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); + } + + return (int)index; + } + + public void Insert(int index, object item) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + + InsertAtHelper(_vector, (uint)index, item); + } + + public void Remove(object item) + { + uint index; + bool exists = _vector.IndexOf(item, out index); + + if (exists) + { + if (((uint)int.MaxValue) < index) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); + } + + RemoveAtHelper(_vector, index); + } + } + + public void RemoveAt(int index) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + + RemoveAtHelper(_vector, (uint)index); + } + + private static object GetAt(global::Microsoft.UI.Xaml.Interop.IBindableVector _this, uint index) + { + try + { + return _this.GetAt(index); + + // We delegate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + throw; + } + } + + private static void SetAt(global::Microsoft.UI.Xaml.Interop.IBindableVector _this, uint index, object value) + { + try + { + _this.SetAt(index, value); + + // We delegate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + throw; + } + } + + private static void InsertAtHelper(global::Microsoft.UI.Xaml.Interop.IBindableVector _this, uint index, object item) + { + try + { + _this.InsertAt(index, item); + + // We delegate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + throw; + } + } + + private static void RemoveAtHelper(global::Microsoft.UI.Xaml.Interop.IBindableVector _this, uint index) + { + try + { + _this.RemoveAt(index); + + // We delegate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + throw; + } + } + + public IEnumerator GetEnumerator() + { + return ((IEnumerable)(IWinRTObject)_vector).GetEnumerator(); + } + } + + public sealed class ToAbiHelper : IBindableVector + { + private global::System.Collections.IList _list; + + public ToAbiHelper(global::System.Collections.IList list) => _list = list; + + public object GetAt(uint index) + { + EnsureIndexInt32(index, _list.Count); + + try + { + return _list[(int)index]; + } + catch (ArgumentOutOfRangeException ex) + { + throw ex.GetExceptionForHR(ExceptionHelpers.E_BOUNDS, ErrorStrings.ArgumentOutOfRange_Index); + } + } + + public uint Size { get => (uint)_list.Count; } + + IBindableVectorView IBindableVector.GetView() + { + return new ListToBindableVectorViewAdapter(_list); + } + + public bool IndexOf(object value, out uint index) + { + int ind = _list.IndexOf(value); + + if (-1 == ind) + { + index = 0; + return false; + } + + index = (uint)ind; + return true; + } + + public void SetAt(uint index, object value) + { + EnsureIndexInt32(index, _list.Count); + + try + { + _list[(int)index] = value; + } + catch (ArgumentOutOfRangeException ex) + { + throw ex.GetExceptionForHR(ExceptionHelpers.E_BOUNDS, ErrorStrings.ArgumentOutOfRange_Index); + } + } + + public void InsertAt(uint index, object value) + { + // Inserting at an index one past the end of the list is equivalent to appending + // so we need to ensure that we're within (0, count + 1). + EnsureIndexInt32(index, _list.Count + 1); + + try + { + _list.Insert((int)index, value); + } + catch (ArgumentOutOfRangeException ex) + { + // Change error code to match what WinRT expects + ex.SetHResult(ExceptionHelpers.E_BOUNDS); + throw; + } + } + + public void RemoveAt(uint index) + { + EnsureIndexInt32(index, _list.Count); + + try + { + _list.RemoveAt((int)index); + } + catch (ArgumentOutOfRangeException ex) + { + // Change error code to match what WinRT expects + ex.SetHResult(ExceptionHelpers.E_BOUNDS); + throw; + } + } + + public void Append(object value) + { + _list.Add(value); + } + + public void RemoveAtEnd() + { + if (_list.Count == 0) + { + Exception e = new InvalidOperationException(ErrorStrings.InvalidOperation_CannotRemoveLastFromEmptyCollection); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + + uint size = (uint)_list.Count; + RemoveAt(size - 1); + } + + public void Clear() + { + _list.Clear(); + } + + private static void EnsureIndexInt32(uint index, int listCapacity) + { + // We use '<=' and not '<' becasue int.MaxValue == index would imply + // that Size > int.MaxValue: + if (((uint)int.MaxValue) <= index || index >= (uint)listCapacity) + { + Exception e = new ArgumentOutOfRangeException(nameof(index), ErrorStrings.ArgumentOutOfRange_IndexLargerThanMaxValue); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + } + + public IEnumerator GetEnumerator() => _list.GetEnumerator(); + + /// A Windows Runtime IBindableVectorView implementation that wraps around a managed IList exposing + /// it to Windows runtime interop. + internal sealed class ListToBindableVectorViewAdapter : IBindableVectorView + { + private readonly global::System.Collections.IList list; + + internal ListToBindableVectorViewAdapter(global::System.Collections.IList list) + { + if (list == null) + throw new ArgumentNullException(nameof(list)); + this.list = list; + } + + private static void EnsureIndexInt32(uint index, int listCapacity) + { + // We use '<=' and not '<' becasue int.MaxValue == index would imply + // that Size > int.MaxValue: + if (((uint)int.MaxValue) <= index || index >= (uint)listCapacity) + { + Exception e = new ArgumentOutOfRangeException(nameof(index), ErrorStrings.ArgumentOutOfRange_IndexLargerThanMaxValue); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + } + + public IBindableIterator First() => + IEnumerable.ToAbiHelper.MakeBindableIterator(list.GetEnumerator()); + + public object GetAt(uint index) + { + EnsureIndexInt32(index, list.Count); + + try + { + return list[(int)index]; + } + catch (ArgumentOutOfRangeException ex) + { + throw ex.GetExceptionForHR(ExceptionHelpers.E_BOUNDS, ErrorStrings.ArgumentOutOfRange_Index); + } + } + + public uint Size => (uint)list.Count; + + public bool IndexOf(object value, out uint index) + { + int ind = list.IndexOf(value); + + if (-1 == ind) + { + index = 0; + return false; + } + + index = (uint)ind; + return true; + } + + public IEnumerator GetEnumerator() => list.GetEnumerator(); + } + } + + [Guid("393DE7DE-6FD0-4C0D-BB71-47244A113E93")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + private void* _GetAt_0; + private void* _get_Size_1; + private void* _GetView_2; + private void* _IndexOf_3; + private void* _SetAt_4; + private void* _InsertAt_5; + private void* _RemoveAt_6; + private void* _Append_7; + private void* _RemoveAtEnd_8; + private void* _Clear_9; + + public delegate* stdcall GetAt_0 { get => (delegate* stdcall)_GetAt_0; set => _GetAt_0 = value; } + public delegate* stdcall get_Size_1 { get => (delegate* stdcall)_get_Size_1; set => _get_Size_1 = value; } + public delegate* stdcall GetView_2 { get => (delegate* stdcall)_GetView_2; set => _GetView_2 = value; } + public delegate* stdcall IndexOf_3 { get => (delegate* stdcall)_IndexOf_3; set => _IndexOf_3 = value; } + public delegate* stdcall SetAt_4 { get => (delegate* stdcall)_SetAt_4; set => _SetAt_4 = value; } + public delegate* stdcall InsertAt_5 { get => (delegate* stdcall)_InsertAt_5; set => _InsertAt_5 = value; } + public delegate* stdcall RemoveAt_6 { get => (delegate* stdcall)_RemoveAt_6; set => _RemoveAt_6 = value; } + public delegate* stdcall Append_7 { get => (delegate* stdcall)_Append_7; set => _Append_7 = value; } + public delegate* stdcall RemoveAtEnd_8 { get => (delegate* stdcall)_RemoveAtEnd_8; set => _RemoveAtEnd_8 = value; } + public delegate* stdcall Clear_9 { get => (delegate* stdcall)_Clear_9; set => _Clear_9 = value; } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + _GetAt_0 = (delegate*)&Do_Abi_GetAt_0, + _get_Size_1 = (delegate*)&Do_Abi_get_Size_1, + _GetView_2 = (delegate*)&Do_Abi_GetView_2, + _IndexOf_3 = (delegate*)&Do_Abi_IndexOf_3, + _SetAt_4 = (delegate*)&Do_Abi_SetAt_4, + _InsertAt_5 = (delegate*)&Do_Abi_InsertAt_5, + _RemoveAt_6 = (delegate*)&Do_Abi_RemoveAt_6, + _Append_7 = (delegate*)&Do_Abi_Append_7, + _RemoveAtEnd_8 = (delegate*)&Do_Abi_RemoveAtEnd_8, + _Clear_9 = (delegate*)&Do_Abi_Clear_9, + + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 10); + Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable _adapterTable = + new ConditionalWeakTable(); + + private static IBindableVector FindAdapter(IntPtr thisPtr) + { + var __this = global::WinRT.ComWrappersSupport.FindObject(thisPtr); + return _adapterTable.GetValue(__this, (list) => new ToAbiHelper(list)); + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetAt_0(IntPtr thisPtr, uint index, IntPtr* result) + { + object __result = default; + *result = default; + try + { + __result = FindAdapter(thisPtr).GetAt(index); + *result = MarshalInspectable.FromManaged(__result); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetView_2(IntPtr thisPtr, IntPtr* result) + { + global::Microsoft.UI.Xaml.Interop.IBindableVectorView __result = default; + *result = default; + try + { + __result = FindAdapter(thisPtr).GetView(); + *result = MarshalInterface.FromManaged(__result); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_IndexOf_3(IntPtr thisPtr, IntPtr value, uint* index, byte* returnValue) + { + bool __returnValue = default; + *index = default; + *returnValue = default; + uint __index = default; + try + { + __returnValue = FindAdapter(thisPtr).IndexOf(MarshalInspectable.FromAbi(value), out __index); + *index = __index; + *returnValue = (byte)(__returnValue ? 1 : 0); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_SetAt_4(IntPtr thisPtr, uint index, IntPtr value) + { + try + { + FindAdapter(thisPtr).SetAt(index, MarshalInspectable.FromAbi(value)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_InsertAt_5(IntPtr thisPtr, uint index, IntPtr value) + { + try + { + FindAdapter(thisPtr).InsertAt(index, MarshalInspectable.FromAbi(value)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_RemoveAt_6(IntPtr thisPtr, uint index) + { + try + { + FindAdapter(thisPtr).RemoveAt(index); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_Append_7(IntPtr thisPtr, IntPtr value) + { + try + { + FindAdapter(thisPtr).Append(MarshalInspectable.FromAbi(value)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_RemoveAtEnd_8(IntPtr thisPtr) + { + try + { + FindAdapter(thisPtr).RemoveAtEnd(); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_Clear_9(IntPtr thisPtr) + { + try + { + FindAdapter(thisPtr).Clear(); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, uint* value) + { + uint __value = default; + + *value = default; + + try + { + __value = FindAdapter(thisPtr).Size; + *value = __value; + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + internal static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + return ObjectReference.FromAbi(thisPtr); + } + + private static FromAbiHelper _VectorToList(IWinRTObject _this) + { + return (FromAbiHelper)_this.GetOrCreateTypeHelperData(typeof(global::System.Collections.IList).TypeHandle, + () => new FromAbiHelper((global::Microsoft.UI.Xaml.Interop.IBindableVector)_this)); + } + + unsafe object global::Microsoft.UI.Xaml.Interop.IBindableVector.GetAt(uint index) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetAt_0(ThisPtr, index, &__retval)); + return MarshalInspectable.FromAbi(__retval); + } + finally + { + MarshalInspectable.DisposeAbi(__retval); + } + } + + unsafe global::Microsoft.UI.Xaml.Interop.IBindableVectorView global::Microsoft.UI.Xaml.Interop.IBindableVector.GetView() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetView_2(ThisPtr, &__retval)); + return MarshalInterface.FromAbi(__retval); + } + finally + { + MarshalInterface.DisposeAbi(__retval); + } + } + + unsafe bool global::Microsoft.UI.Xaml.Interop.IBindableVector.IndexOf(object value, out uint index) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IObjectReference __value = default; + uint __index = default; + byte __retval = default; + try + { + __value = MarshalInspectable.CreateMarshaler(value); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.IndexOf_3(ThisPtr, MarshalInspectable.GetAbi(__value), &__index, &__retval)); + index = __index; + return __retval != 0; + } + finally + { + MarshalInspectable.DisposeMarshaler(__value); + } + } + + unsafe void global::Microsoft.UI.Xaml.Interop.IBindableVector.SetAt(uint index, object value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IObjectReference __value = default; + try + { + __value = MarshalInspectable.CreateMarshaler(value); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.SetAt_4(ThisPtr, index, MarshalInspectable.GetAbi(__value))); + } + finally + { + MarshalInspectable.DisposeMarshaler(__value); + } + } + + unsafe void global::Microsoft.UI.Xaml.Interop.IBindableVector.InsertAt(uint index, object value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IObjectReference __value = default; + try + { + __value = MarshalInspectable.CreateMarshaler(value); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.InsertAt_5(ThisPtr, index, MarshalInspectable.GetAbi(__value))); + } + finally + { + MarshalInspectable.DisposeMarshaler(__value); + } + } + + unsafe void global::Microsoft.UI.Xaml.Interop.IBindableVector.RemoveAt(uint index) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RemoveAt_6(ThisPtr, index)); + } + + unsafe void global::Microsoft.UI.Xaml.Interop.IBindableVector.Append(object value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IObjectReference __value = default; + try + { + __value = MarshalInspectable.CreateMarshaler(value); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Append_7(ThisPtr, MarshalInspectable.GetAbi(__value))); + } + finally + { + MarshalInspectable.DisposeMarshaler(__value); + } + } + + unsafe void global::Microsoft.UI.Xaml.Interop.IBindableVector.RemoveAtEnd() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RemoveAtEnd_8(ThisPtr)); + } + + unsafe void global::Microsoft.UI.Xaml.Interop.IBindableVector.Clear() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Clear_9(ThisPtr)); + } + + unsafe uint global::Microsoft.UI.Xaml.Interop.IBindableVector.Size + { + get + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + uint __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, &__retval)); + return __retval; + } + } + + object global::System.Collections.IList.this[int index] + { + get => _VectorToList((IWinRTObject)this)[index]; + + set => _VectorToList((IWinRTObject)this)[index] = value; + } + + bool global::System.Collections.IList.IsFixedSize => _VectorToList((IWinRTObject)this).IsFixedSize; + + bool global::System.Collections.IList.IsReadOnly => _VectorToList((IWinRTObject)this).IsReadOnly; + + int global::System.Collections.ICollection.Count => _VectorToList((IWinRTObject)this).Count; + + bool global::System.Collections.ICollection.IsSynchronized => _VectorToList((IWinRTObject)this).IsSynchronized; + + object global::System.Collections.ICollection.SyncRoot => _VectorToList((IWinRTObject)this).SyncRoot; + + int global::System.Collections.IList.Add(object value) => _VectorToList((IWinRTObject)this).Add(value); + + void global::System.Collections.IList.Clear() => _VectorToList((IWinRTObject)this).Clear(); + + bool global::System.Collections.IList.Contains(object value) => _VectorToList((IWinRTObject)this).Contains(value); + + int global::System.Collections.IList.IndexOf(object value) => _VectorToList((IWinRTObject)this).IndexOf(value); + + void global::System.Collections.IList.Insert(int index, object value) => _VectorToList((IWinRTObject)this).Insert(index, value); + + void global::System.Collections.IList.Remove(object value) => _VectorToList((IWinRTObject)this).Remove(value); + + void global::System.Collections.IList.RemoveAt(int index) => _VectorToList((IWinRTObject)this).RemoveAt(index); + + void global::System.Collections.ICollection.CopyTo(Array array, int index) => _VectorToList((IWinRTObject)this).CopyTo(array, index); + + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => _VectorToList((IWinRTObject)this).GetEnumerator(); + } + internal static class IList_Delegates + { + public unsafe delegate int GetAt_0(IntPtr thisPtr, uint index, IntPtr* result); + public unsafe delegate int get_Size_1(IntPtr thisPtr, uint* result); + public unsafe delegate int GetView_2(IntPtr thisPtr, IntPtr* result); + public unsafe delegate int IndexOf_3(IntPtr thisPtr, IntPtr value, uint* index, byte* returnValue); + public unsafe delegate int SetAt_4(IntPtr thisPtr, uint index, IntPtr value); + public unsafe delegate int InsertAt_5(IntPtr thisPtr, uint index, IntPtr value); + public unsafe delegate int RemoveAt_6(IntPtr thisPtr, uint index); + public unsafe delegate int Append_7(IntPtr thisPtr, IntPtr value); + public unsafe delegate int RemoveAtEnd_8(IntPtr thisPtr); + public unsafe delegate int Clear_9(IntPtr thisPtr); + } +} diff --git a/WinRT.Runtime/Projections/Bindable.cs b/WinRT.Runtime/Projections/Bindable.netstandard2.0.cs similarity index 95% rename from WinRT.Runtime/Projections/Bindable.cs rename to WinRT.Runtime/Projections/Bindable.netstandard2.0.cs index da9005b3f..d62f99c8b 100644 --- a/WinRT.Runtime/Projections/Bindable.cs +++ b/WinRT.Runtime/Projections/Bindable.netstandard2.0.cs @@ -74,32 +74,26 @@ public struct Vftbl private static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 + private static readonly Delegate[] DelegateCache = new Delegate[3]; -#endif + static unsafe Vftbl() { AbiToProjectionVftable = new Vftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 + _get_Current_0 = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new IBindableIterator_Delegates.get_Current_0(Do_Abi_get_Current_0)).ToPointer(), _get_HasCurrent_1 = Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new IBindableIterator_Delegates.get_HasCurrent_1(Do_Abi_get_HasCurrent_1)).ToPointer(), _MoveNext_2 = Marshal.GetFunctionPointerForDelegate(DelegateCache[2] = new IBindableIterator_Delegates.MoveNext_2(Do_Abi_MoveNext_2)).ToPointer(), -#else - _get_Current_0 = (delegate*)&Do_Abi_get_Current_0, - _get_HasCurrent_1 = (delegate*)&Do_Abi_get_HasCurrent_1, - _MoveNext_2 = (delegate*)&Do_Abi_MoveNext_2 -#endif + }; var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 3); Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_MoveNext_2(IntPtr thisPtr, byte* result) { bool __result = default; @@ -116,9 +110,7 @@ private static unsafe int Do_Abi_MoveNext_2(IntPtr thisPtr, byte* result) } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_get_Current_0(IntPtr thisPtr, IntPtr* value) { object __value = default; @@ -135,9 +127,7 @@ private static unsafe int Do_Abi_get_Current_0(IntPtr thisPtr, IntPtr* value) } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_get_HasCurrent_1(IntPtr thisPtr, byte* value) { bool __value = default; @@ -229,32 +219,26 @@ public struct Vftbl private static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 + private static readonly Delegate[] DelegateCache = new Delegate[3]; -#endif + static unsafe Vftbl() { AbiToProjectionVftable = new Vftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 + _GetAt_0 = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new IBindableVectorView_Delegates.GetAt_0(Do_Abi_GetAt_0)).ToPointer(), _get_Size_1 = Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new IBindableVectorView_Delegates.get_Size_1(Do_Abi_get_Size_1)).ToPointer(), _IndexOf_2 = Marshal.GetFunctionPointerForDelegate(DelegateCache[2] = new IBindableVectorView_Delegates.IndexOf_2(Do_Abi_IndexOf_2)).ToPointer(), -#else - _GetAt_0 = (delegate*)&Do_Abi_GetAt_0, - _get_Size_1 = (delegate*)&Do_Abi_get_Size_1, - _IndexOf_2 = (delegate*)&Do_Abi_IndexOf_2 -#endif + }; var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 3); Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_GetAt_0(IntPtr thisPtr, uint index, IntPtr* result) { object __result = default; @@ -272,9 +256,7 @@ private static unsafe int Do_Abi_GetAt_0(IntPtr thisPtr, uint index, IntPtr* res } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_IndexOf_2(IntPtr thisPtr, IntPtr value, uint* index, byte* returnValue) { bool __returnValue = default; @@ -297,9 +279,7 @@ private static unsafe int Do_Abi_IndexOf_2(IntPtr thisPtr, IntPtr value, uint* i } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, uint* value) { uint __value = default; @@ -463,28 +443,24 @@ public struct Vftbl private static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 + private static readonly IEnumerable_Delegates.First_0 DelegateCache; -#endif + static unsafe Vftbl() { AbiToProjectionVftable = new Vftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 + _First_0 = Marshal.GetFunctionPointerForDelegate(DelegateCache = Do_Abi_First_0).ToPointer() -#else - _First_0 = (delegate* )&Do_Abi_First_0 -#endif + }; var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 1); Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_First_0(IntPtr thisPtr, IntPtr* result) { *result = default; @@ -1009,15 +985,15 @@ public struct Vftbl private static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 + private static readonly Delegate[] DelegateCache = new Delegate[10]; -#endif + static unsafe Vftbl() { AbiToProjectionVftable = new Vftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 + _GetAt_0 = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new IList_Delegates.GetAt_0(Do_Abi_GetAt_0)).ToPointer(), _get_Size_1 = Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new IList_Delegates.get_Size_1(Do_Abi_get_Size_1)).ToPointer(), _GetView_2 = Marshal.GetFunctionPointerForDelegate(DelegateCache[2] = new IList_Delegates.GetView_2(Do_Abi_GetView_2)).ToPointer(), @@ -1028,18 +1004,7 @@ static unsafe Vftbl() _Append_7 = Marshal.GetFunctionPointerForDelegate(DelegateCache[7] = new IList_Delegates.Append_7(Do_Abi_Append_7)).ToPointer(), _RemoveAtEnd_8 = Marshal.GetFunctionPointerForDelegate(DelegateCache[8] = new IList_Delegates.RemoveAtEnd_8(Do_Abi_RemoveAtEnd_8)).ToPointer(), _Clear_9 = Marshal.GetFunctionPointerForDelegate(DelegateCache[9] = new IList_Delegates.Clear_9(Do_Abi_Clear_9)).ToPointer(), -#else - _GetAt_0 = (delegate*)&Do_Abi_GetAt_0, - _get_Size_1 = (delegate*)&Do_Abi_get_Size_1, - _GetView_2 = (delegate*)&Do_Abi_GetView_2, - _IndexOf_3 = (delegate*)&Do_Abi_IndexOf_3, - _SetAt_4 = (delegate*)&Do_Abi_SetAt_4, - _InsertAt_5 = (delegate*)&Do_Abi_InsertAt_5, - _RemoveAt_6 = (delegate*)&Do_Abi_RemoveAt_6, - _Append_7 = (delegate*)&Do_Abi_Append_7, - _RemoveAtEnd_8 = (delegate*)&Do_Abi_RemoveAtEnd_8, - _Clear_9 = (delegate*)&Do_Abi_Clear_9, -#endif + }; var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 10); Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); @@ -1055,9 +1020,7 @@ private static IBindableVector FindAdapter(IntPtr thisPtr) return _adapterTable.GetValue(__this, (list) => new ToAbiHelper(list)); } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_GetAt_0(IntPtr thisPtr, uint index, IntPtr* result) { object __result = default; @@ -1075,9 +1038,7 @@ private static unsafe int Do_Abi_GetAt_0(IntPtr thisPtr, uint index, IntPtr* res } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_GetView_2(IntPtr thisPtr, IntPtr* result) { global::Microsoft.UI.Xaml.Interop.IBindableVectorView __result = default; @@ -1094,9 +1055,7 @@ private static unsafe int Do_Abi_GetView_2(IntPtr thisPtr, IntPtr* result) } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_IndexOf_3(IntPtr thisPtr, IntPtr value, uint* index, byte* returnValue) { bool __returnValue = default; @@ -1116,9 +1075,7 @@ private static unsafe int Do_Abi_IndexOf_3(IntPtr thisPtr, IntPtr value, uint* i } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_SetAt_4(IntPtr thisPtr, uint index, IntPtr value) { try @@ -1132,9 +1089,7 @@ private static unsafe int Do_Abi_SetAt_4(IntPtr thisPtr, uint index, IntPtr valu } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_InsertAt_5(IntPtr thisPtr, uint index, IntPtr value) { try @@ -1148,9 +1103,7 @@ private static unsafe int Do_Abi_InsertAt_5(IntPtr thisPtr, uint index, IntPtr v } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_RemoveAt_6(IntPtr thisPtr, uint index) { try @@ -1164,9 +1117,7 @@ private static unsafe int Do_Abi_RemoveAt_6(IntPtr thisPtr, uint index) } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_Append_7(IntPtr thisPtr, IntPtr value) { try @@ -1180,9 +1131,7 @@ private static unsafe int Do_Abi_Append_7(IntPtr thisPtr, IntPtr value) } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_RemoveAtEnd_8(IntPtr thisPtr) { try @@ -1196,9 +1145,7 @@ private static unsafe int Do_Abi_RemoveAtEnd_8(IntPtr thisPtr) } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_Clear_9(IntPtr thisPtr) { try @@ -1212,9 +1159,7 @@ private static unsafe int Do_Abi_Clear_9(IntPtr thisPtr) } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, uint* value) { uint __value = default; diff --git a/WinRT.Runtime/Projections/EventHandler.cs b/WinRT.Runtime/Projections/EventHandler.net5.cs similarity index 99% rename from WinRT.Runtime/Projections/EventHandler.cs rename to WinRT.Runtime/Projections/EventHandler.net5.cs index 0fe73563e..b1704ad5f 100644 --- a/WinRT.Runtime/Projections/EventHandler.cs +++ b/WinRT.Runtime/Projections/EventHandler.net5.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq.Expressions; @@ -35,10 +35,10 @@ static EventHandler() public static global::System.Delegate AbiInvokeDelegate { get; } - public static unsafe IObjectReference CreateMarshaler(global::System.EventHandler managedDelegate) => + public static unsafe IObjectReference CreateMarshaler(global::System.EventHandler managedDelegate) => managedDelegate is null ? null : ComWrappersSupport.CreateCCWForObject(managedDelegate).As(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) @@ -50,25 +50,25 @@ public static IntPtr GetAbi(IObjectReference value) => [global::WinRT.ObjectReferenceWrapper(nameof(_nativeDelegate))] private class NativeDelegateWrapper { - private readonly ObjectReference _nativeDelegate; - private readonly AgileReference _agileReference = default; + private readonly ObjectReference _nativeDelegate; + private readonly AgileReference _agileReference = default; public NativeDelegateWrapper(ObjectReference nativeDelegate) { - _nativeDelegate = nativeDelegate; - if (_nativeDelegate.TryAs(out var objRef) < 0) - { - _agileReference = new AgileReference(_nativeDelegate); - } - else - { - objRef.Dispose(); - } + _nativeDelegate = nativeDelegate; + if (_nativeDelegate.TryAs(out var objRef) < 0) + { + _agileReference = new AgileReference(_nativeDelegate); + } + else + { + objRef.Dispose(); + } } public void Invoke(object sender, T args) - { - using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(EventHandler))); + { + using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(EventHandler))); var delegateToInvoke = agileDelegate ?? _nativeDelegate; IntPtr ThisPtr = delegateToInvoke.ThisPtr; var abiInvoke = Marshal.GetDelegateForFunctionPointer(delegateToInvoke.Vftbl.Invoke, Abi_Invoke_Type); @@ -92,7 +92,7 @@ public void Invoke(object sender, T args) } } - public static IntPtr FromManaged(global::System.EventHandler managedDelegate) => + public static IntPtr FromManaged(global::System.EventHandler managedDelegate) => CreateMarshaler(managedDelegate)?.GetRef() ?? IntPtr.Zero; public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper>.DisposeMarshaler(value); diff --git a/WinRT.Runtime/Projections/EventHandler.netstandard2.0.cs b/WinRT.Runtime/Projections/EventHandler.netstandard2.0.cs new file mode 100644 index 000000000..b1704ad5f --- /dev/null +++ b/WinRT.Runtime/Projections/EventHandler.netstandard2.0.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using WinRT; +using WinRT.Interop; + +namespace ABI.System +{ + [Guid("9DE1C535-6AE1-11E0-84E1-18A905BCC53F"), EditorBrowsable(EditorBrowsableState.Never)] + public 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) }); + + private static readonly global::WinRT.Interop.IDelegateVftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static EventHandler() + { + AbiInvokeDelegate = global::System.Delegate.CreateDelegate(Abi_Invoke_Type, typeof(EventHandler).GetMethod(nameof(Do_Abi_Invoke), BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(new global::System.Type[] { Marshaler.AbiType }) + ); + AbiToProjectionVftable = new global::WinRT.Interop.IDelegateVftbl + { + IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, + Invoke = Marshal.GetFunctionPointerForDelegate(AbiInvokeDelegate) + }; + var nativeVftbl = ComWrappersSupport.AllocateVtableMemory(typeof(EventHandler), Marshal.SizeOf()); + Marshal.StructureToPtr(AbiToProjectionVftable, nativeVftbl, false); + AbiToProjectionVftablePtr = nativeVftbl; + } + + public static global::System.Delegate AbiInvokeDelegate { get; } + + public static unsafe IObjectReference CreateMarshaler(global::System.EventHandler managedDelegate) => + managedDelegate is null ? null : ComWrappersSupport.CreateCCWForObject(managedDelegate).As(GuidGenerator.GetIID(typeof(EventHandler))); + + 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 = ObjectReference.FromAbi(nativeDelegate); + return (global::System.EventHandler)ComWrappersSupport.TryRegisterObjectForInterface(new global::System.EventHandler(new NativeDelegateWrapper(abiDelegate).Invoke), nativeDelegate); + } + + [global::WinRT.ObjectReferenceWrapper(nameof(_nativeDelegate))] + private class NativeDelegateWrapper + { + private readonly ObjectReference _nativeDelegate; + private readonly AgileReference _agileReference = default; + + public NativeDelegateWrapper(ObjectReference nativeDelegate) + { + _nativeDelegate = nativeDelegate; + if (_nativeDelegate.TryAs(out var objRef) < 0) + { + _agileReference = new AgileReference(_nativeDelegate); + } + else + { + objRef.Dispose(); + } + } + + public void Invoke(object sender, T args) + { + using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(EventHandler))); + var delegateToInvoke = agileDelegate ?? _nativeDelegate; + IntPtr ThisPtr = delegateToInvoke.ThisPtr; + var abiInvoke = Marshal.GetDelegateForFunctionPointer(delegateToInvoke.Vftbl.Invoke, Abi_Invoke_Type); + IObjectReference __sender = default; + object __args = default; + var __params = new object[] { ThisPtr, null, null }; + try + { + __sender = MarshalInspectable.CreateMarshaler(sender); + __params[1] = MarshalInspectable.GetAbi(__sender); + __args = Marshaler.CreateMarshaler(args); + __params[2] = Marshaler.GetAbi(__args); + abiInvoke.DynamicInvokeAbi(__params); + } + finally + { + MarshalInspectable.DisposeMarshaler(__sender); + Marshaler.DisposeMarshaler(__args); + } + + } + } + + public static IntPtr FromManaged(global::System.EventHandler managedDelegate) => + CreateMarshaler(managedDelegate)?.GetRef() ?? IntPtr.Zero; + + public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper>.DisposeMarshaler(value); + + public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper>.DisposeAbi(abi); + + private static unsafe int Do_Abi_Invoke(void* thisPtr, IntPtr sender, TAbi args) + { + try + { + global::WinRT.ComWrappersSupport.MarshalDelegateInvoke(new IntPtr(thisPtr), (global::System.Delegate invoke) => + { + invoke.DynamicInvoke(MarshalInspectable.FromAbi(sender), Marshaler.FromAbi(args)); + }); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } +} diff --git a/WinRT.Runtime/Projections/Geometry.cs b/WinRT.Runtime/Projections/Geometry.net5.cs similarity index 96% rename from WinRT.Runtime/Projections/Geometry.cs rename to WinRT.Runtime/Projections/Geometry.net5.cs index 1bb5cd976..e50622a3b 100644 --- a/WinRT.Runtime/Projections/Geometry.cs +++ b/WinRT.Runtime/Projections/Geometry.net5.cs @@ -1,591 +1,591 @@ -using System; -using System.Globalization; -using System.Runtime.InteropServices; - -namespace Windows.Foundation -{ - internal class SR - { - public static string ArgumentOutOfRange_NeedNonNegNum = "Non-negative number required."; - } - - [global::WinRT.WindowsRuntimeType] - [StructLayout(LayoutKind.Sequential)] - public struct Point : IFormattable - { - public float _x; - public float _y; - - public Point(float x, float y) - { - _x = x; - _y = y; - } - - public Point(double x, double y) : this((float)x, (float)y) { } - - public double X - { - get { return _x; } - set { _x = (float)value; } - } - - public double Y - { - get { return _y; } - set { _y = (float)value; } - } - - public override string ToString() - { - return ConvertToString(null, null); - } - - public string ToString(IFormatProvider provider) - { - return ConvertToString(null, provider); - } - - string IFormattable.ToString(string format, IFormatProvider provider) - { - return ConvertToString(format, provider); - } - - private string ConvertToString(string format, IFormatProvider provider) - { - char separator = GetNumericListSeparator(provider); - return string.Format(provider, "{1:" + format + "}{0}{2:" + format + "}", separator, _x, _y); - } - - static char GetNumericListSeparator(IFormatProvider provider) - { - // If the decimal separator is a comma use ';' - char numericSeparator = ','; - var numberFormat = NumberFormatInfo.GetInstance(provider); - if ((numberFormat.NumberDecimalSeparator.Length > 0) && (numberFormat.NumberDecimalSeparator[0] == numericSeparator)) - { - numericSeparator = ';'; - } - - return numericSeparator; - } - - public static bool operator ==(Point point1, Point point2) - { - return point1._x == point2._x && point1._y == point2._y; - } - - public static bool operator !=(Point point1, Point point2) - { - return !(point1 == point2); - } - - public override bool Equals(object o) - { - return o is Point && this == (Point)o; - } - - public bool Equals(Point value) - { - return (this == value); - } - - public override int GetHashCode() - { - return X.GetHashCode() ^ Y.GetHashCode(); - } - } - - [global::WinRT.WindowsRuntimeType] - [StructLayout(LayoutKind.Sequential)] - public struct Rect : IFormattable - { - public float _x; - public float _y; - public float _width; - public float _height; - - private const double EmptyX = double.PositiveInfinity; - private const double EmptyY = double.PositiveInfinity; - private const double EmptyWidth = double.NegativeInfinity; - private const double EmptyHeight = double.NegativeInfinity; - - private static readonly Rect s_empty = CreateEmptyRect(); - - public Rect(float x, - float y, - float width, - float height) - { - if (width < 0) - throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum); - if (height < 0) - throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum); - - _x = x; - _y = y; - _width = width; - _height = height; - } - - public Rect(double x, - double y, - double width, - double height) : this((float)x, (float)y, (float)width, (float)height) { } - - public Rect(Point point1, - Point point2) - { - _x = Math.Min(point1._x, point2._x); - _y = Math.Min(point1._y, point2._y); - - _width = Math.Max(Math.Max(point1._x, point2._x) - _x, 0f); - _height = Math.Max(Math.Max(point1._y, point2._y) - _y, 0f); - } - - public Rect(Point location, Size size) - { - if (size.IsEmpty) - { - this = s_empty; - } - else - { - _x = location._x; - _y = location._y; - _width = size._width; - _height = size._height; - } - } - - public double X - { - get { return _x; } - set { _x = (float)value; } - } - - public double Y - { - get { return _y; } - set { _y = (float)value; } - } - - public double Width - { - get { return _width; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum); - - _width = (float)value; - } - } - - public double Height - { - get { return _height; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum); - - _height = (float)value; - } - } - - public double Left - { - get { return _x; } - } - - public double Top - { - get { return _y; } - } - - public double Right - { - get - { - if (IsEmpty) - { - return double.NegativeInfinity; - } - - return _x + _width; - } - } - - public double Bottom - { - get - { - if (IsEmpty) - { - return double.NegativeInfinity; - } - - return _y + _height; - } - } - - public static Rect Empty - { - get { return s_empty; } - } - - public bool IsEmpty - { - get { return _width < 0; } - } - - public bool Contains(Point point) - { - return ContainsInternal(point._x, point._y); - } - - public void Intersect(Rect rect) - { - if (!this.IntersectsWith(rect)) - { - this = s_empty; - } - else - { - double left = Math.Max(X, rect.X); - double top = Math.Max(Y, rect.Y); - - // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) - Width = Math.Max(Math.Min(X + Width, rect.X + rect.Width) - left, 0); - Height = Math.Max(Math.Min(Y + Height, rect.Y + rect.Height) - top, 0); - - X = left; - Y = top; - } - } - - public void Union(Rect rect) - { - if (IsEmpty) - { - this = rect; - } - else if (!rect.IsEmpty) - { - double left = Math.Min(Left, rect.Left); - double top = Math.Min(Top, rect.Top); - - - // We need this check so that the math does not result in NaN - if ((rect.Width == double.PositiveInfinity) || (Width == double.PositiveInfinity)) - { - Width = double.PositiveInfinity; - } - else - { - // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) - double maxRight = Math.Max(Right, rect.Right); - Width = Math.Max(maxRight - left, 0); - } - - // We need this check so that the math does not result in NaN - if ((rect.Height == double.PositiveInfinity) || (Height == double.PositiveInfinity)) - { - Height = double.PositiveInfinity; - } - else - { - // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) - double maxBottom = Math.Max(Bottom, rect.Bottom); - Height = Math.Max(maxBottom - top, 0); - } - - X = left; - Y = top; - } - } - - public void Union(Point point) - { - Union(new Rect(point, point)); - } - - private bool ContainsInternal(float x, float y) - { - return ((x >= _x) && (x - _width <= _x) && - (y >= _y) && (y - _height <= _y)); - } - - internal bool IntersectsWith(Rect rect) - { - if (_width < 0 || rect._width < 0) - { - return false; - } - - return (rect._x <= _x + _width) && - (rect._x + rect._width >= _x) && - (rect._y <= _y + _height) && - (rect._y + rect._height >= _y); - } - - private static Rect CreateEmptyRect() - { - Rect rect = default; - - rect._x = (float)EmptyX; - rect._y = (float)EmptyY; - - // the width and height properties prevent assignment of - // negative numbers so assign directly to the backing fields. - rect._width = (float)EmptyWidth; - rect._height = (float)EmptyHeight; - - return rect; - } - - public override string ToString() - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null /* format string */, null /* format provider */); - } - - public string ToString(IFormatProvider provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null /* format string */, provider); - } - - string IFormattable.ToString(string format, IFormatProvider provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(format, provider); - } - - - internal string ConvertToString(string format, IFormatProvider provider) - { - if (IsEmpty) - { - return "Empty."; - } - - // Helper to get the numeric list separator for a given culture. - char separator = TokenizerHelper.GetNumericListSeparator(provider); - return string.Format(provider, - "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}", - separator, - _x, - _y, - _width, - _height); - } - - public bool Equals(Rect value) - { - return (this == value); - } - - public static bool operator ==(Rect rect1, Rect rect2) - { - return rect1._x == rect2._x && - rect1._y == rect2._y && - rect1._width == rect2._width && - rect1._height == rect2._height; - } - - public static bool operator !=(Rect rect1, Rect rect2) - { - return !(rect1 == rect2); - } - - public override bool Equals(object o) - { - return o is Rect && this == (Rect)o; - } - - public override int GetHashCode() - { - // Perform field-by-field XOR of HashCodes - return X.GetHashCode() ^ - Y.GetHashCode() ^ - Width.GetHashCode() ^ - Height.GetHashCode(); - } - } - - [global::WinRT.WindowsRuntimeType] - [StructLayout(LayoutKind.Sequential)] - public struct Size - { - public float _width; - public float _height; - - private static readonly Size s_empty = CreateEmptySize(); - - public Size(float width, float height) - { - if (width < 0) - throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum); - if (height < 0) - throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum); - _width = width; - _height = height; - } - - public Size(double width, double height) : this((float)width, (float)height) { } - - public double Width - { - get { return _width; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum); - - _width = (float)value; - } - } - - public double Height - { - get { return _height; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum); - - _height = (float)value; - } - } - - public static Size Empty - { - get { return s_empty; } - } - - - public bool IsEmpty - { - get { return Width < 0; } - } - - private static Size CreateEmptySize() - { - Size size = default; - // We can't set these via the property setters because negatives widths - // are rejected in those APIs. - size._width = float.NegativeInfinity; - size._height = float.NegativeInfinity; - return size; - } - - public static bool operator ==(Size size1, Size size2) - { - return size1._width == size2._width && - size1._height == size2._height; - } - - public static bool operator !=(Size size1, Size size2) - { - return !(size1 == size2); - } - - public override bool Equals(object o) - { - return o is Size && Size.Equals(this, (Size)o); - } - - public bool Equals(Size value) - { - return Size.Equals(this, value); - } - - public override int GetHashCode() - { - if (IsEmpty) - { - return 0; - } - else - { - // Perform field-by-field XOR of HashCodes - return Width.GetHashCode() ^ - Height.GetHashCode(); - } - } - - private static bool Equals(Size size1, Size size2) - { - if (size1.IsEmpty) - { - return size2.IsEmpty; - } - else - { - return size1._width.Equals(size2._width) && - size1._height.Equals(size2._height); - } - } - - public override string ToString() - { - if (IsEmpty) - { - return "Empty"; - } - - return string.Format("{0},{1}", _width, _height); - } - } - - public static class TokenizerHelper - { - public static char GetNumericListSeparator(IFormatProvider provider) - { - char numericSeparator = ','; - - // Get the NumberFormatInfo out of the provider, if possible - // If the IFormatProvider doesn't not contain a NumberFormatInfo, then - // this method returns the current culture's NumberFormatInfo. - NumberFormatInfo numberFormat = NumberFormatInfo.GetInstance(provider); - - // Is the decimal separator is the same as the list separator? - // If so, we use the ";". - if ((numberFormat.NumberDecimalSeparator.Length > 0) && (numericSeparator == numberFormat.NumberDecimalSeparator[0])) - { - numericSeparator = ';'; - } - - return numericSeparator; - } - } -} - -namespace ABI.Windows.Foundation -{ - public static class Point - { - public static string GetGuidSignature() - { - return "struct(Windows.Foundation.Point;f4;f4)"; - } - } - - public static class Rect - { - public static string GetGuidSignature() - { - return "struct(Windows.Foundation.Rect;f4;f4;f4;f4)"; - } - } - - public static class Size - { - public static string GetGuidSignature() - { - return "struct(Windows.Foundation.Size;f4;f4)"; - } - } +using System; +using System.Globalization; +using System.Runtime.InteropServices; + +namespace Windows.Foundation +{ + internal class SR + { + public static string ArgumentOutOfRange_NeedNonNegNum = "Non-negative number required."; + } + + [global::WinRT.WindowsRuntimeType] + [StructLayout(LayoutKind.Sequential)] + public struct Point : IFormattable + { + public float _x; + public float _y; + + public Point(float x, float y) + { + _x = x; + _y = y; + } + + public Point(double x, double y) : this((float)x, (float)y) { } + + public double X + { + get { return _x; } + set { _x = (float)value; } + } + + public double Y + { + get { return _y; } + set { _y = (float)value; } + } + + public override string ToString() + { + return ConvertToString(null, null); + } + + public string ToString(IFormatProvider provider) + { + return ConvertToString(null, provider); + } + + string IFormattable.ToString(string format, IFormatProvider provider) + { + return ConvertToString(format, provider); + } + + private string ConvertToString(string format, IFormatProvider provider) + { + char separator = GetNumericListSeparator(provider); + return string.Format(provider, "{1:" + format + "}{0}{2:" + format + "}", separator, _x, _y); + } + + static char GetNumericListSeparator(IFormatProvider provider) + { + // If the decimal separator is a comma use ';' + char numericSeparator = ','; + var numberFormat = NumberFormatInfo.GetInstance(provider); + if ((numberFormat.NumberDecimalSeparator.Length > 0) && (numberFormat.NumberDecimalSeparator[0] == numericSeparator)) + { + numericSeparator = ';'; + } + + return numericSeparator; + } + + public static bool operator ==(Point point1, Point point2) + { + return point1._x == point2._x && point1._y == point2._y; + } + + public static bool operator !=(Point point1, Point point2) + { + return !(point1 == point2); + } + + public override bool Equals(object o) + { + return o is Point && this == (Point)o; + } + + public bool Equals(Point value) + { + return (this == value); + } + + public override int GetHashCode() + { + return X.GetHashCode() ^ Y.GetHashCode(); + } + } + + [global::WinRT.WindowsRuntimeType] + [StructLayout(LayoutKind.Sequential)] + public struct Rect : IFormattable + { + public float _x; + public float _y; + public float _width; + public float _height; + + private const double EmptyX = double.PositiveInfinity; + private const double EmptyY = double.PositiveInfinity; + private const double EmptyWidth = double.NegativeInfinity; + private const double EmptyHeight = double.NegativeInfinity; + + private static readonly Rect s_empty = CreateEmptyRect(); + + public Rect(float x, + float y, + float width, + float height) + { + if (width < 0) + throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum); + if (height < 0) + throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum); + + _x = x; + _y = y; + _width = width; + _height = height; + } + + public Rect(double x, + double y, + double width, + double height) : this((float)x, (float)y, (float)width, (float)height) { } + + public Rect(Point point1, + Point point2) + { + _x = Math.Min(point1._x, point2._x); + _y = Math.Min(point1._y, point2._y); + + _width = Math.Max(Math.Max(point1._x, point2._x) - _x, 0f); + _height = Math.Max(Math.Max(point1._y, point2._y) - _y, 0f); + } + + public Rect(Point location, Size size) + { + if (size.IsEmpty) + { + this = s_empty; + } + else + { + _x = location._x; + _y = location._y; + _width = size._width; + _height = size._height; + } + } + + public double X + { + get { return _x; } + set { _x = (float)value; } + } + + public double Y + { + get { return _y; } + set { _y = (float)value; } + } + + public double Width + { + get { return _width; } + set + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum); + + _width = (float)value; + } + } + + public double Height + { + get { return _height; } + set + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum); + + _height = (float)value; + } + } + + public double Left + { + get { return _x; } + } + + public double Top + { + get { return _y; } + } + + public double Right + { + get + { + if (IsEmpty) + { + return double.NegativeInfinity; + } + + return _x + _width; + } + } + + public double Bottom + { + get + { + if (IsEmpty) + { + return double.NegativeInfinity; + } + + return _y + _height; + } + } + + public static Rect Empty + { + get { return s_empty; } + } + + public bool IsEmpty + { + get { return _width < 0; } + } + + public bool Contains(Point point) + { + return ContainsInternal(point._x, point._y); + } + + public void Intersect(Rect rect) + { + if (!this.IntersectsWith(rect)) + { + this = s_empty; + } + else + { + double left = Math.Max(X, rect.X); + double top = Math.Max(Y, rect.Y); + + // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) + Width = Math.Max(Math.Min(X + Width, rect.X + rect.Width) - left, 0); + Height = Math.Max(Math.Min(Y + Height, rect.Y + rect.Height) - top, 0); + + X = left; + Y = top; + } + } + + public void Union(Rect rect) + { + if (IsEmpty) + { + this = rect; + } + else if (!rect.IsEmpty) + { + double left = Math.Min(Left, rect.Left); + double top = Math.Min(Top, rect.Top); + + + // We need this check so that the math does not result in NaN + if ((rect.Width == double.PositiveInfinity) || (Width == double.PositiveInfinity)) + { + Width = double.PositiveInfinity; + } + else + { + // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) + double maxRight = Math.Max(Right, rect.Right); + Width = Math.Max(maxRight - left, 0); + } + + // We need this check so that the math does not result in NaN + if ((rect.Height == double.PositiveInfinity) || (Height == double.PositiveInfinity)) + { + Height = double.PositiveInfinity; + } + else + { + // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) + double maxBottom = Math.Max(Bottom, rect.Bottom); + Height = Math.Max(maxBottom - top, 0); + } + + X = left; + Y = top; + } + } + + public void Union(Point point) + { + Union(new Rect(point, point)); + } + + private bool ContainsInternal(float x, float y) + { + return ((x >= _x) && (x - _width <= _x) && + (y >= _y) && (y - _height <= _y)); + } + + internal bool IntersectsWith(Rect rect) + { + if (_width < 0 || rect._width < 0) + { + return false; + } + + return (rect._x <= _x + _width) && + (rect._x + rect._width >= _x) && + (rect._y <= _y + _height) && + (rect._y + rect._height >= _y); + } + + private static Rect CreateEmptyRect() + { + Rect rect = default; + + rect._x = (float)EmptyX; + rect._y = (float)EmptyY; + + // the width and height properties prevent assignment of + // negative numbers so assign directly to the backing fields. + rect._width = (float)EmptyWidth; + rect._height = (float)EmptyHeight; + + return rect; + } + + public override string ToString() + { + // Delegate to the internal method which implements all ToString calls. + return ConvertToString(null /* format string */, null /* format provider */); + } + + public string ToString(IFormatProvider provider) + { + // Delegate to the internal method which implements all ToString calls. + return ConvertToString(null /* format string */, provider); + } + + string IFormattable.ToString(string format, IFormatProvider provider) + { + // Delegate to the internal method which implements all ToString calls. + return ConvertToString(format, provider); + } + + + internal string ConvertToString(string format, IFormatProvider provider) + { + if (IsEmpty) + { + return "Empty."; + } + + // Helper to get the numeric list separator for a given culture. + char separator = TokenizerHelper.GetNumericListSeparator(provider); + return string.Format(provider, + "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}", + separator, + _x, + _y, + _width, + _height); + } + + public bool Equals(Rect value) + { + return (this == value); + } + + public static bool operator ==(Rect rect1, Rect rect2) + { + return rect1._x == rect2._x && + rect1._y == rect2._y && + rect1._width == rect2._width && + rect1._height == rect2._height; + } + + public static bool operator !=(Rect rect1, Rect rect2) + { + return !(rect1 == rect2); + } + + public override bool Equals(object o) + { + return o is Rect && this == (Rect)o; + } + + public override int GetHashCode() + { + // Perform field-by-field XOR of HashCodes + return X.GetHashCode() ^ + Y.GetHashCode() ^ + Width.GetHashCode() ^ + Height.GetHashCode(); + } + } + + [global::WinRT.WindowsRuntimeType] + [StructLayout(LayoutKind.Sequential)] + public struct Size + { + public float _width; + public float _height; + + private static readonly Size s_empty = CreateEmptySize(); + + public Size(float width, float height) + { + if (width < 0) + throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum); + if (height < 0) + throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum); + _width = width; + _height = height; + } + + public Size(double width, double height) : this((float)width, (float)height) { } + + public double Width + { + get { return _width; } + set + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum); + + _width = (float)value; + } + } + + public double Height + { + get { return _height; } + set + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum); + + _height = (float)value; + } + } + + public static Size Empty + { + get { return s_empty; } + } + + + public bool IsEmpty + { + get { return Width < 0; } + } + + private static Size CreateEmptySize() + { + Size size = default; + // We can't set these via the property setters because negatives widths + // are rejected in those APIs. + size._width = float.NegativeInfinity; + size._height = float.NegativeInfinity; + return size; + } + + public static bool operator ==(Size size1, Size size2) + { + return size1._width == size2._width && + size1._height == size2._height; + } + + public static bool operator !=(Size size1, Size size2) + { + return !(size1 == size2); + } + + public override bool Equals(object o) + { + return o is Size && Size.Equals(this, (Size)o); + } + + public bool Equals(Size value) + { + return Size.Equals(this, value); + } + + public override int GetHashCode() + { + if (IsEmpty) + { + return 0; + } + else + { + // Perform field-by-field XOR of HashCodes + return Width.GetHashCode() ^ + Height.GetHashCode(); + } + } + + private static bool Equals(Size size1, Size size2) + { + if (size1.IsEmpty) + { + return size2.IsEmpty; + } + else + { + return size1._width.Equals(size2._width) && + size1._height.Equals(size2._height); + } + } + + public override string ToString() + { + if (IsEmpty) + { + return "Empty"; + } + + return string.Format("{0},{1}", _width, _height); + } + } + + public static class TokenizerHelper + { + public static char GetNumericListSeparator(IFormatProvider provider) + { + char numericSeparator = ','; + + // Get the NumberFormatInfo out of the provider, if possible + // If the IFormatProvider doesn't not contain a NumberFormatInfo, then + // this method returns the current culture's NumberFormatInfo. + NumberFormatInfo numberFormat = NumberFormatInfo.GetInstance(provider); + + // Is the decimal separator is the same as the list separator? + // If so, we use the ";". + if ((numberFormat.NumberDecimalSeparator.Length > 0) && (numericSeparator == numberFormat.NumberDecimalSeparator[0])) + { + numericSeparator = ';'; + } + + return numericSeparator; + } + } +} + +namespace ABI.Windows.Foundation +{ + public static class Point + { + public static string GetGuidSignature() + { + return "struct(Windows.Foundation.Point;f4;f4)"; + } + } + + public static class Rect + { + public static string GetGuidSignature() + { + return "struct(Windows.Foundation.Rect;f4;f4;f4;f4)"; + } + } + + public static class Size + { + public static string GetGuidSignature() + { + return "struct(Windows.Foundation.Size;f4;f4)"; + } + } } \ No newline at end of file diff --git a/WinRT.Runtime/Projections/Geometry.netstandard2.0.cs b/WinRT.Runtime/Projections/Geometry.netstandard2.0.cs new file mode 100644 index 000000000..e50622a3b --- /dev/null +++ b/WinRT.Runtime/Projections/Geometry.netstandard2.0.cs @@ -0,0 +1,591 @@ +using System; +using System.Globalization; +using System.Runtime.InteropServices; + +namespace Windows.Foundation +{ + internal class SR + { + public static string ArgumentOutOfRange_NeedNonNegNum = "Non-negative number required."; + } + + [global::WinRT.WindowsRuntimeType] + [StructLayout(LayoutKind.Sequential)] + public struct Point : IFormattable + { + public float _x; + public float _y; + + public Point(float x, float y) + { + _x = x; + _y = y; + } + + public Point(double x, double y) : this((float)x, (float)y) { } + + public double X + { + get { return _x; } + set { _x = (float)value; } + } + + public double Y + { + get { return _y; } + set { _y = (float)value; } + } + + public override string ToString() + { + return ConvertToString(null, null); + } + + public string ToString(IFormatProvider provider) + { + return ConvertToString(null, provider); + } + + string IFormattable.ToString(string format, IFormatProvider provider) + { + return ConvertToString(format, provider); + } + + private string ConvertToString(string format, IFormatProvider provider) + { + char separator = GetNumericListSeparator(provider); + return string.Format(provider, "{1:" + format + "}{0}{2:" + format + "}", separator, _x, _y); + } + + static char GetNumericListSeparator(IFormatProvider provider) + { + // If the decimal separator is a comma use ';' + char numericSeparator = ','; + var numberFormat = NumberFormatInfo.GetInstance(provider); + if ((numberFormat.NumberDecimalSeparator.Length > 0) && (numberFormat.NumberDecimalSeparator[0] == numericSeparator)) + { + numericSeparator = ';'; + } + + return numericSeparator; + } + + public static bool operator ==(Point point1, Point point2) + { + return point1._x == point2._x && point1._y == point2._y; + } + + public static bool operator !=(Point point1, Point point2) + { + return !(point1 == point2); + } + + public override bool Equals(object o) + { + return o is Point && this == (Point)o; + } + + public bool Equals(Point value) + { + return (this == value); + } + + public override int GetHashCode() + { + return X.GetHashCode() ^ Y.GetHashCode(); + } + } + + [global::WinRT.WindowsRuntimeType] + [StructLayout(LayoutKind.Sequential)] + public struct Rect : IFormattable + { + public float _x; + public float _y; + public float _width; + public float _height; + + private const double EmptyX = double.PositiveInfinity; + private const double EmptyY = double.PositiveInfinity; + private const double EmptyWidth = double.NegativeInfinity; + private const double EmptyHeight = double.NegativeInfinity; + + private static readonly Rect s_empty = CreateEmptyRect(); + + public Rect(float x, + float y, + float width, + float height) + { + if (width < 0) + throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum); + if (height < 0) + throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum); + + _x = x; + _y = y; + _width = width; + _height = height; + } + + public Rect(double x, + double y, + double width, + double height) : this((float)x, (float)y, (float)width, (float)height) { } + + public Rect(Point point1, + Point point2) + { + _x = Math.Min(point1._x, point2._x); + _y = Math.Min(point1._y, point2._y); + + _width = Math.Max(Math.Max(point1._x, point2._x) - _x, 0f); + _height = Math.Max(Math.Max(point1._y, point2._y) - _y, 0f); + } + + public Rect(Point location, Size size) + { + if (size.IsEmpty) + { + this = s_empty; + } + else + { + _x = location._x; + _y = location._y; + _width = size._width; + _height = size._height; + } + } + + public double X + { + get { return _x; } + set { _x = (float)value; } + } + + public double Y + { + get { return _y; } + set { _y = (float)value; } + } + + public double Width + { + get { return _width; } + set + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum); + + _width = (float)value; + } + } + + public double Height + { + get { return _height; } + set + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum); + + _height = (float)value; + } + } + + public double Left + { + get { return _x; } + } + + public double Top + { + get { return _y; } + } + + public double Right + { + get + { + if (IsEmpty) + { + return double.NegativeInfinity; + } + + return _x + _width; + } + } + + public double Bottom + { + get + { + if (IsEmpty) + { + return double.NegativeInfinity; + } + + return _y + _height; + } + } + + public static Rect Empty + { + get { return s_empty; } + } + + public bool IsEmpty + { + get { return _width < 0; } + } + + public bool Contains(Point point) + { + return ContainsInternal(point._x, point._y); + } + + public void Intersect(Rect rect) + { + if (!this.IntersectsWith(rect)) + { + this = s_empty; + } + else + { + double left = Math.Max(X, rect.X); + double top = Math.Max(Y, rect.Y); + + // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) + Width = Math.Max(Math.Min(X + Width, rect.X + rect.Width) - left, 0); + Height = Math.Max(Math.Min(Y + Height, rect.Y + rect.Height) - top, 0); + + X = left; + Y = top; + } + } + + public void Union(Rect rect) + { + if (IsEmpty) + { + this = rect; + } + else if (!rect.IsEmpty) + { + double left = Math.Min(Left, rect.Left); + double top = Math.Min(Top, rect.Top); + + + // We need this check so that the math does not result in NaN + if ((rect.Width == double.PositiveInfinity) || (Width == double.PositiveInfinity)) + { + Width = double.PositiveInfinity; + } + else + { + // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) + double maxRight = Math.Max(Right, rect.Right); + Width = Math.Max(maxRight - left, 0); + } + + // We need this check so that the math does not result in NaN + if ((rect.Height == double.PositiveInfinity) || (Height == double.PositiveInfinity)) + { + Height = double.PositiveInfinity; + } + else + { + // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) + double maxBottom = Math.Max(Bottom, rect.Bottom); + Height = Math.Max(maxBottom - top, 0); + } + + X = left; + Y = top; + } + } + + public void Union(Point point) + { + Union(new Rect(point, point)); + } + + private bool ContainsInternal(float x, float y) + { + return ((x >= _x) && (x - _width <= _x) && + (y >= _y) && (y - _height <= _y)); + } + + internal bool IntersectsWith(Rect rect) + { + if (_width < 0 || rect._width < 0) + { + return false; + } + + return (rect._x <= _x + _width) && + (rect._x + rect._width >= _x) && + (rect._y <= _y + _height) && + (rect._y + rect._height >= _y); + } + + private static Rect CreateEmptyRect() + { + Rect rect = default; + + rect._x = (float)EmptyX; + rect._y = (float)EmptyY; + + // the width and height properties prevent assignment of + // negative numbers so assign directly to the backing fields. + rect._width = (float)EmptyWidth; + rect._height = (float)EmptyHeight; + + return rect; + } + + public override string ToString() + { + // Delegate to the internal method which implements all ToString calls. + return ConvertToString(null /* format string */, null /* format provider */); + } + + public string ToString(IFormatProvider provider) + { + // Delegate to the internal method which implements all ToString calls. + return ConvertToString(null /* format string */, provider); + } + + string IFormattable.ToString(string format, IFormatProvider provider) + { + // Delegate to the internal method which implements all ToString calls. + return ConvertToString(format, provider); + } + + + internal string ConvertToString(string format, IFormatProvider provider) + { + if (IsEmpty) + { + return "Empty."; + } + + // Helper to get the numeric list separator for a given culture. + char separator = TokenizerHelper.GetNumericListSeparator(provider); + return string.Format(provider, + "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}", + separator, + _x, + _y, + _width, + _height); + } + + public bool Equals(Rect value) + { + return (this == value); + } + + public static bool operator ==(Rect rect1, Rect rect2) + { + return rect1._x == rect2._x && + rect1._y == rect2._y && + rect1._width == rect2._width && + rect1._height == rect2._height; + } + + public static bool operator !=(Rect rect1, Rect rect2) + { + return !(rect1 == rect2); + } + + public override bool Equals(object o) + { + return o is Rect && this == (Rect)o; + } + + public override int GetHashCode() + { + // Perform field-by-field XOR of HashCodes + return X.GetHashCode() ^ + Y.GetHashCode() ^ + Width.GetHashCode() ^ + Height.GetHashCode(); + } + } + + [global::WinRT.WindowsRuntimeType] + [StructLayout(LayoutKind.Sequential)] + public struct Size + { + public float _width; + public float _height; + + private static readonly Size s_empty = CreateEmptySize(); + + public Size(float width, float height) + { + if (width < 0) + throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum); + if (height < 0) + throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum); + _width = width; + _height = height; + } + + public Size(double width, double height) : this((float)width, (float)height) { } + + public double Width + { + get { return _width; } + set + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum); + + _width = (float)value; + } + } + + public double Height + { + get { return _height; } + set + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum); + + _height = (float)value; + } + } + + public static Size Empty + { + get { return s_empty; } + } + + + public bool IsEmpty + { + get { return Width < 0; } + } + + private static Size CreateEmptySize() + { + Size size = default; + // We can't set these via the property setters because negatives widths + // are rejected in those APIs. + size._width = float.NegativeInfinity; + size._height = float.NegativeInfinity; + return size; + } + + public static bool operator ==(Size size1, Size size2) + { + return size1._width == size2._width && + size1._height == size2._height; + } + + public static bool operator !=(Size size1, Size size2) + { + return !(size1 == size2); + } + + public override bool Equals(object o) + { + return o is Size && Size.Equals(this, (Size)o); + } + + public bool Equals(Size value) + { + return Size.Equals(this, value); + } + + public override int GetHashCode() + { + if (IsEmpty) + { + return 0; + } + else + { + // Perform field-by-field XOR of HashCodes + return Width.GetHashCode() ^ + Height.GetHashCode(); + } + } + + private static bool Equals(Size size1, Size size2) + { + if (size1.IsEmpty) + { + return size2.IsEmpty; + } + else + { + return size1._width.Equals(size2._width) && + size1._height.Equals(size2._height); + } + } + + public override string ToString() + { + if (IsEmpty) + { + return "Empty"; + } + + return string.Format("{0},{1}", _width, _height); + } + } + + public static class TokenizerHelper + { + public static char GetNumericListSeparator(IFormatProvider provider) + { + char numericSeparator = ','; + + // Get the NumberFormatInfo out of the provider, if possible + // If the IFormatProvider doesn't not contain a NumberFormatInfo, then + // this method returns the current culture's NumberFormatInfo. + NumberFormatInfo numberFormat = NumberFormatInfo.GetInstance(provider); + + // Is the decimal separator is the same as the list separator? + // If so, we use the ";". + if ((numberFormat.NumberDecimalSeparator.Length > 0) && (numericSeparator == numberFormat.NumberDecimalSeparator[0])) + { + numericSeparator = ';'; + } + + return numericSeparator; + } + } +} + +namespace ABI.Windows.Foundation +{ + public static class Point + { + public static string GetGuidSignature() + { + return "struct(Windows.Foundation.Point;f4;f4)"; + } + } + + public static class Rect + { + public static string GetGuidSignature() + { + return "struct(Windows.Foundation.Rect;f4;f4;f4;f4)"; + } + } + + public static class Size + { + public static string GetGuidSignature() + { + return "struct(Windows.Foundation.Size;f4;f4)"; + } + } +} \ No newline at end of file diff --git a/WinRT.Runtime/Projections/ICommand.net5.cs b/WinRT.Runtime/Projections/ICommand.net5.cs new file mode 100644 index 000000000..489919f87 --- /dev/null +++ b/WinRT.Runtime/Projections/ICommand.net5.cs @@ -0,0 +1,324 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using WinRT; +using WinRT.Interop; + +namespace ABI.System.Windows.Input +{ + [Guid("c50898f6-c536-5f47-8583-8b2c2438a13b")] + internal static class CanExecuteChangedEventHandler + { + private delegate int Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr args); + + private static readonly global::WinRT.Interop.IDelegateVftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static CanExecuteChangedEventHandler() + { + AbiInvokeDelegate = (Abi_Invoke)Do_Abi_Invoke; + AbiToProjectionVftable = new global::WinRT.Interop.IDelegateVftbl + { + IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, + Invoke = Marshal.GetFunctionPointerForDelegate(AbiInvokeDelegate) + }; + var nativeVftbl = ComWrappersSupport.AllocateVtableMemory(typeof(CanExecuteChangedEventHandler), Marshal.SizeOf()); + Marshal.StructureToPtr(AbiToProjectionVftable, nativeVftbl, false); + AbiToProjectionVftablePtr = nativeVftbl; + } + + public static global::System.Delegate AbiInvokeDelegate { get; } + + public static unsafe IObjectReference CreateMarshaler(global::System.EventHandler managedDelegate) => + managedDelegate is null ? null : ComWrappersSupport.CreateCCWForObject(managedDelegate).As(GuidGenerator.GetIID(typeof(CanExecuteChangedEventHandler))); + + 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 = ObjectReference.FromAbi(nativeDelegate); + return (global::System.EventHandler)ComWrappersSupport.TryRegisterObjectForInterface(new global::System.EventHandler(new NativeDelegateWrapper(abiDelegate).Invoke), nativeDelegate); + } + + [global::WinRT.ObjectReferenceWrapper(nameof(_nativeDelegate))] + private class NativeDelegateWrapper + { + private readonly ObjectReference _nativeDelegate; + private readonly AgileReference _agileReference = default; + + public NativeDelegateWrapper(ObjectReference nativeDelegate) + { + _nativeDelegate = nativeDelegate; + if (_nativeDelegate.TryAs(out var objRef) < 0) + { + _agileReference = new AgileReference(_nativeDelegate); + } + else + { + objRef.Dispose(); + } + } + + public void Invoke(object sender, EventArgs args) + { + using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(CanExecuteChangedEventHandler))); + var delegateToInvoke = agileDelegate ?? _nativeDelegate; + IntPtr ThisPtr = delegateToInvoke.ThisPtr; + var abiInvoke = Marshal.GetDelegateForFunctionPointer(delegateToInvoke.Vftbl.Invoke); + IObjectReference __sender = default; + IObjectReference __args = default; + var __params = new object[] { ThisPtr, null, null }; + try + { + __sender = MarshalInspectable.CreateMarshaler(sender); + __params[1] = MarshalInspectable.GetAbi(__sender); + __args = MarshalInspectable.CreateMarshaler(args); + __params[2] = MarshalInspectable.GetAbi(__args); + abiInvoke.DynamicInvokeAbi(__params); + } + finally + { + MarshalInspectable.DisposeMarshaler(__sender); + MarshalInspectable.DisposeMarshaler(__args); + } + + } + } + + public static IntPtr FromManaged(global::System.EventHandler managedDelegate) => + CreateMarshaler(managedDelegate)?.GetRef() ?? IntPtr.Zero; + + public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper>.DisposeMarshaler(value); + + public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper>.DisposeAbi(abi); + + private static unsafe int Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr args) + { + try + { + global::WinRT.ComWrappersSupport.MarshalDelegateInvoke(thisPtr, (global::System.Delegate invoke) => + { + invoke.DynamicInvoke( + MarshalInspectable.FromAbi(sender), + MarshalInspectable.FromAbi(args) as EventArgs ?? EventArgs.Empty); + }); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + + internal sealed unsafe class CanExecuteChangedEventSource : EventSource + { + internal CanExecuteChangedEventSource(IObjectReference obj, + delegate* stdcall addHandler, + delegate* stdcall removeHandler) + : base(obj, addHandler, removeHandler) + { + } + + protected override IObjectReference CreateMarshaler(EventHandler del) => + del is null ? null : CanExecuteChangedEventHandler.CreateMarshaler(del); + + protected override void DisposeMarshaler(IObjectReference marshaler) => + CanExecuteChangedEventHandler.DisposeMarshaler(marshaler); + + protected override IntPtr GetAbi(IObjectReference marshaler) => + marshaler is null ? IntPtr.Zero : CanExecuteChangedEventHandler.GetAbi(marshaler); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Guid("E5AF3542-CA67-4081-995B-709DD13792DF")] + [DynamicInterfaceCastableImplementation] + public unsafe interface ICommand : global::System.Windows.Input.ICommand + { + [Guid("E5AF3542-CA67-4081-995B-709DD13792DF")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + private void* _add_CanExecuteChanged_0; + public delegate* stdcall add_CanExecuteChanged_0 { get => (delegate* stdcall)_add_CanExecuteChanged_0; set => _add_CanExecuteChanged_0 = value; } + private void* _remove_CanExecuteChanged_1; + public delegate* stdcall remove_CanExecuteChanged_1 { get => (delegate* stdcall)_remove_CanExecuteChanged_1; set => _remove_CanExecuteChanged_1 = value; } + private void* _CanExecute_2; + public delegate* stdcall CanExecute_2 { get => (delegate* stdcall)_CanExecute_2; set => _CanExecute_2 = value; } + private void* _Execute_3; + public delegate* stdcall Execute_3 { get => (delegate* stdcall)_Execute_3; set => _Execute_3 = value; } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + _add_CanExecuteChanged_0 = (delegate*)&Do_Abi_add_CanExecuteChanged_0, + _remove_CanExecuteChanged_1 = (delegate*)&Do_Abi_remove_CanExecuteChanged_1, + _CanExecute_2 = (delegate*)&Do_Abi_CanExecute_2, + _Execute_3 = (delegate*)&Do_Abi_Execute_3, + + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 4); + Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_CanExecute_2(IntPtr thisPtr, IntPtr parameter, byte* result) + { + bool __result = default; + + result = default; + + try + { + __result = global::WinRT.ComWrappersSupport.FindObject(thisPtr).CanExecute(MarshalInspectable.FromAbi(parameter)); *result = (byte)(__result ? 1 : 0); + + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_Execute_3(IntPtr thisPtr, IntPtr parameter) + { + try + { + global::WinRT.ComWrappersSupport.FindObject(thisPtr).Execute(MarshalInspectable.FromAbi(parameter)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + private static ConditionalWeakTable> _CanExecuteChanged_TokenTables = new ConditionalWeakTable>(); + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_add_CanExecuteChanged_0(IntPtr thisPtr, IntPtr handler, global::WinRT.EventRegistrationToken* token) + { + token = default; + try + { + var __this = global::WinRT.ComWrappersSupport.FindObject(thisPtr); + var __handler = CanExecuteChangedEventHandler.FromAbi(handler); + *token = _CanExecuteChanged_TokenTables.GetOrCreateValue(__this).AddEventHandler(__handler); + __this.CanExecuteChanged += __handler; + return 0; + } + catch (global::System.Exception __ex) + { + return __ex.HResult; + } + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_remove_CanExecuteChanged_1(IntPtr thisPtr, global::WinRT.EventRegistrationToken token) + { + try + { + var __this = global::WinRT.ComWrappersSupport.FindObject(thisPtr); + if (_CanExecuteChanged_TokenTables.TryGetValue(__this, out var __table) && __table.RemoveEventHandler(token, out var __handler)) + { + __this.CanExecuteChanged -= __handler; + } + return 0; + } + catch (global::System.Exception __ex) + { + return __ex.HResult; + } + } + } + public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + private static CanExecuteChangedEventSource _CanExecuteChanged(IWinRTObject _this) + { + var _obj = ((ObjectReference)((IWinRTObject)_this).GetObjectReferenceForType(typeof(global::System.Windows.Input.ICommand).TypeHandle)); + + return (CanExecuteChangedEventSource)_this.GetOrCreateTypeHelperData(typeof(global::System.Windows.Input.ICommand).TypeHandle, + () => new CanExecuteChangedEventSource(_obj, _obj.Vftbl.add_CanExecuteChanged_0, _obj.Vftbl.remove_CanExecuteChanged_1)); + } + + unsafe bool global::System.Windows.Input.ICommand.CanExecute(object parameter) + { + IObjectReference __parameter = default; + byte __retval = default; + try + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Windows.Input.ICommand).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + __parameter = MarshalInspectable.CreateMarshaler(parameter); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.CanExecute_2(ThisPtr, MarshalInspectable.GetAbi(__parameter), out __retval)); + return __retval != 0; + } + finally + { + MarshalInspectable.DisposeMarshaler(__parameter); + } + } + + unsafe void global::System.Windows.Input.ICommand.Execute(object parameter) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Windows.Input.ICommand).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IObjectReference __parameter = default; + try + { + __parameter = MarshalInspectable.CreateMarshaler(parameter); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Execute_3(ThisPtr, MarshalInspectable.GetAbi(__parameter))); + } + finally + { + MarshalInspectable.DisposeMarshaler(__parameter); + } + } + + event global::System.EventHandler global::System.Windows.Input.ICommand.CanExecuteChanged + { + add + { + _CanExecuteChanged((IWinRTObject)this).Subscribe(value); + } + remove + { + _CanExecuteChanged((IWinRTObject)this).Unsubscribe(value); + } + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public 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); + public unsafe delegate int Execute_3(IntPtr thisPtr, IntPtr parameter); + } +} diff --git a/WinRT.Runtime/Projections/ICommand.cs b/WinRT.Runtime/Projections/ICommand.netstandard2.0.cs similarity index 95% rename from WinRT.Runtime/Projections/ICommand.cs rename to WinRT.Runtime/Projections/ICommand.netstandard2.0.cs index 695538c27..9314345f8 100644 --- a/WinRT.Runtime/Projections/ICommand.cs +++ b/WinRT.Runtime/Projections/ICommand.netstandard2.0.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq.Expressions; @@ -156,35 +156,27 @@ public struct Vftbl private static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 + private static Delegate[] DelegateCache = new Delegate[4]; -#endif + static unsafe Vftbl() { AbiToProjectionVftable = new Vftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 + _add_CanExecuteChanged_0 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ICommand_Delegates.add_CanExecuteChanged_0(Do_Abi_add_CanExecuteChanged_0)), _remove_CanExecuteChanged_1 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new _remove_EventHandler(Do_Abi_remove_CanExecuteChanged_1)), _CanExecute_2 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ICommand_Delegates.CanExecute_2(Do_Abi_CanExecute_2)), _Execute_3 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ICommand_Delegates.Execute_3(Do_Abi_Execute_3)), -#else - _add_CanExecuteChanged_0 = (delegate*)&Do_Abi_add_CanExecuteChanged_0, - _remove_CanExecuteChanged_1 = (delegate*)&Do_Abi_remove_CanExecuteChanged_1, - _CanExecute_2 = (delegate*)&Do_Abi_CanExecute_2, - _Execute_3 = (delegate*)&Do_Abi_Execute_3, -#endif + }; var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 4); Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_CanExecute_2(IntPtr thisPtr, IntPtr parameter, byte* result) { bool __result = default; @@ -204,9 +196,7 @@ private static unsafe int Do_Abi_CanExecute_2(IntPtr thisPtr, IntPtr parameter, return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_Execute_3(IntPtr thisPtr, IntPtr parameter) { try @@ -223,9 +213,7 @@ private static unsafe int Do_Abi_Execute_3(IntPtr thisPtr, IntPtr parameter) private static ConditionalWeakTable> _CanExecuteChanged_TokenTables = new ConditionalWeakTable>(); -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_add_CanExecuteChanged_0(IntPtr thisPtr, IntPtr handler, global::WinRT.EventRegistrationToken* token) { token = default; @@ -243,9 +231,7 @@ private static unsafe int Do_Abi_add_CanExecuteChanged_0(IntPtr thisPtr, IntPtr } } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_remove_CanExecuteChanged_1(IntPtr thisPtr, global::WinRT.EventRegistrationToken token) { try diff --git a/WinRT.Runtime/Projections/ICustomPropertyProvider.net5.cs b/WinRT.Runtime/Projections/ICustomPropertyProvider.net5.cs new file mode 100644 index 000000000..95d38e3fe --- /dev/null +++ b/WinRT.Runtime/Projections/ICustomPropertyProvider.net5.cs @@ -0,0 +1,414 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using WinRT; +using WinRT.Interop; + +namespace Microsoft.UI.Xaml.Data +{ + [global::WinRT.WindowsRuntimeType] + [Guid("30DA92C0-23E8-42A0-AE7C-734A0E5D2782")] + interface ICustomProperty + { + object GetValue(object target); + void SetValue(object target, object value); + object GetIndexedValue(object target, object index); + void SetIndexedValue(object target, object value, object index); + bool CanRead { get; } + bool CanWrite { get; } + string Name { get; } + global::System.Type Type { get; } + } +} + +namespace ABI.Microsoft.UI.Xaml.Data +{ + [Guid("30DA92C0-23E8-42A0-AE7C-734A0E5D2782")] + internal unsafe class ICustomProperty + { + [Guid("30DA92C0-23E8-42A0-AE7C-734A0E5D2782")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public void* get_Type_0; + public void* get_Name_1; + public void* GetValue_2; + public void* SetValue_3; + public void* GetIndexedValue_4; + public void* SetIndexedValue_5; + public void* get_CanWrite_6; + public void* get_CanRead_7; + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + get_Type_0 = (delegate*)&Do_Abi_get_Type_0, + get_Name_1 = (delegate*)&Do_Abi_get_Name_1, + GetValue_2 = (delegate*)&Do_Abi_GetValue_2, + SetValue_3 = (delegate*)&Do_Abi_SetValue_3, + GetIndexedValue_4 = (delegate*)&Do_Abi_GetIndexedValue_4, + SetIndexedValue_5 = (delegate*)&Do_Abi_SetIndexedValue_5, + get_CanWrite_6 = (delegate*)&Do_Abi_get_CanWrite_6, + get_CanRead_7 = (delegate*)&Do_Abi_get_CanRead_7 + + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 8); + Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetValue_2(IntPtr thisPtr, IntPtr target, IntPtr* result) + { + object __result = default; + + *result = default; + + try + { + __result = global::WinRT.ComWrappersSupport.FindObject(thisPtr).GetValue(MarshalInspectable.FromAbi(target)); + *result = MarshalInspectable.FromManaged(__result); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_SetValue_3(IntPtr thisPtr, IntPtr target, IntPtr value) + { + + + try + { + global::WinRT.ComWrappersSupport.FindObject(thisPtr).SetValue(MarshalInspectable.FromAbi(target), MarshalInspectable.FromAbi(value)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetIndexedValue_4(IntPtr thisPtr, IntPtr target, IntPtr index, IntPtr* result) + { + object __result = default; + + try + { + __result = global::WinRT.ComWrappersSupport.FindObject(thisPtr).GetIndexedValue(MarshalInspectable.FromAbi(target), MarshalInspectable.FromAbi(index)); + *result = MarshalInspectable.FromManaged(__result); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_SetIndexedValue_5(IntPtr thisPtr, IntPtr target, IntPtr value, IntPtr index) + { + + + try + { + global::WinRT.ComWrappersSupport.FindObject(thisPtr).SetIndexedValue(MarshalInspectable.FromAbi(target), MarshalInspectable.FromAbi(value), MarshalInspectable.FromAbi(index)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_get_CanRead_7(IntPtr thisPtr, byte* value) + { + bool __value = default; + + try + { + __value = global::WinRT.ComWrappersSupport.FindObject(thisPtr).CanRead; *value = (byte)(__value ? 1 : 0); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_get_CanWrite_6(IntPtr thisPtr, byte* value) + { + bool __value = default; + + try + { + __value = global::WinRT.ComWrappersSupport.FindObject(thisPtr).CanWrite; *value = (byte)(__value ? 1 : 0); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_get_Name_1(IntPtr thisPtr, IntPtr* value) + { + string __value = default; + + try + { + __value = global::WinRT.ComWrappersSupport.FindObject(thisPtr).Name; + *value = MarshalString.FromManaged(__value); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_get_Type_0(IntPtr thisPtr, global::ABI.System.Type* value) + { + global::System.Type __value = default; + + try + { + __value = global::WinRT.ComWrappersSupport.FindObject(thisPtr).Type; + *value = global::ABI.System.Type.FromManaged(__value); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + } + internal static class ICustomProperty_Delegates + { + public unsafe delegate int get_Type_0(IntPtr thisPtr, global::ABI.System.Type* value); + public unsafe delegate int get_Name_1(IntPtr thisPtr, IntPtr* value); + public unsafe delegate int GetValue_2(IntPtr thisPtr, IntPtr target, IntPtr* result); + public unsafe delegate int SetValue_3(IntPtr thisPtr, IntPtr target, IntPtr value); + public unsafe delegate int GetIndexedValue_4(IntPtr thisPtr, IntPtr target, IntPtr index, IntPtr* result); + public unsafe delegate int SetIndexedValue_5(IntPtr thisPtr, IntPtr target, IntPtr value, IntPtr index); + public unsafe delegate int get_CanWrite_6(IntPtr thisPtr, byte* value); + public unsafe delegate int get_CanRead_7(IntPtr thisPtr, byte* value); + } + + internal class ManagedCustomProperty : global::Microsoft.UI.Xaml.Data.ICustomProperty + { + private readonly PropertyInfo _property; + + public ManagedCustomProperty(PropertyInfo property) + { + _property = property; + } + + public bool CanRead => _property.CanRead; + + public bool CanWrite => _property.CanWrite; + + public string Name => _property.Name; + + public Type Type => _property.PropertyType; + + public object GetIndexedValue(object target, object index) + { + return _property.GetValue(target, new[] { index }); + } + + public object GetValue(object target) + { + return _property.GetValue(target); + } + + public void SetIndexedValue(object target, object value, object index) + { + _property.SetValue(target, value, new[] { index }); + } + + public void SetValue(object target, object value) + { + _property.SetValue(target, value); + } + } + + [Guid("7C925755-3E48-42B4-8677-76372267033F")] + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct ManagedCustomPropertyProviderVftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + private void* GetCustomProperty_0; + private void* GetIndexedProperty_1; + private void* GetStringRepresentation_2; + private void* get_Type_3; + + private static readonly ManagedCustomPropertyProviderVftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static unsafe ManagedCustomPropertyProviderVftbl() + { + AbiToProjectionVftable = new ManagedCustomPropertyProviderVftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + GetCustomProperty_0 = (delegate*)&Do_Abi_GetCustomProperty_0, + GetIndexedProperty_1 = (delegate*)&Do_Abi_GetIndexedProperty_1, + GetStringRepresentation_2 = (delegate*)&Do_Abi_GetStringRepresentation_2, + get_Type_3 = (delegate*)&Do_Abi_get_Type_3 + + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(ManagedCustomPropertyProviderVftbl), Marshal.SizeOf() + sizeof(IntPtr) * 4); + Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetCustomProperty_0(IntPtr thisPtr, IntPtr name, IntPtr* result) + { + global::Microsoft.UI.Xaml.Data.ICustomProperty __result = default; + try + { + string _name = MarshalString.FromAbi(name); + object target = global::WinRT.ComWrappersSupport.FindObject(thisPtr); + PropertyInfo propertyInfo = target.GetType().GetProperty( + _name, + BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); + + if (propertyInfo is object) + { + __result = new ManagedCustomProperty(propertyInfo); + } + + *result = MarshalInterface.FromManaged(__result); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetIndexedProperty_1(IntPtr thisPtr, IntPtr name, global::ABI.System.Type type, IntPtr* result) + { + global::Microsoft.UI.Xaml.Data.ICustomProperty __result = default; + try + { + string _name = MarshalString.FromAbi(name); + object target = global::WinRT.ComWrappersSupport.FindObject(thisPtr); + PropertyInfo propertyInfo = target.GetType().GetProperty( + _name, + BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, + null, // default binder + null, // ignore return type + new Type[] { global::ABI.System.Type.FromAbi(type) }, // indexed parameter type + null // ignore type modifier + ); + + if (propertyInfo is object) + { + __result = new ManagedCustomProperty(propertyInfo); + } + + *result = MarshalInterface.FromManaged(__result); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetStringRepresentation_2(IntPtr thisPtr, IntPtr* result) + { + string __result = default; + try + { + __result = global::WinRT.ComWrappersSupport.FindObject(thisPtr).ToString(); + *result = MarshalString.FromManaged(__result); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_get_Type_3(IntPtr thisPtr, global::ABI.System.Type* value) + { + global::System.Type __value = default; + try + { + __value = global::WinRT.ComWrappersSupport.FindObject(thisPtr).GetType(); + *value = global::ABI.System.Type.FromManaged(__value); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + + internal static class ICustomPropertyProvider_Delegates + { + public unsafe delegate int GetCustomProperty_0(IntPtr thisPtr, IntPtr name, IntPtr* result); + public unsafe delegate int GetIndexedProperty_1(IntPtr thisPtr, IntPtr name, global::ABI.System.Type type, IntPtr* result); + public unsafe delegate int GetStringRepresentation_2(IntPtr thisPtr, IntPtr* result); + public unsafe delegate int get_Type_3(IntPtr thisPtr, global::ABI.System.Type* value); + } + +} diff --git a/WinRT.Runtime/Projections/ICustomPropertyProvider.cs b/WinRT.Runtime/Projections/ICustomPropertyProvider.netstandard2.0.cs similarity index 89% rename from WinRT.Runtime/Projections/ICustomPropertyProvider.cs rename to WinRT.Runtime/Projections/ICustomPropertyProvider.netstandard2.0.cs index 3de6093ca..f9b8683b7 100644 --- a/WinRT.Runtime/Projections/ICustomPropertyProvider.cs +++ b/WinRT.Runtime/Projections/ICustomPropertyProvider.netstandard2.0.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; @@ -43,15 +43,15 @@ public struct Vftbl private static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 + private static readonly Delegate[] DelegateCache = new Delegate[8]; -#endif + static unsafe Vftbl() { AbiToProjectionVftable = new Vftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 + get_Type_0 = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ICustomProperty_Delegates.get_Type_0(Do_Abi_get_Type_0)).ToPointer(), get_Name_1 = Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new ICustomProperty_Delegates.get_Name_1(Do_Abi_get_Name_1)).ToPointer(), GetValue_2 = Marshal.GetFunctionPointerForDelegate(DelegateCache[2] = new ICustomProperty_Delegates.GetValue_2(Do_Abi_GetValue_2)).ToPointer(), @@ -60,25 +60,14 @@ static unsafe Vftbl() SetIndexedValue_5 = Marshal.GetFunctionPointerForDelegate(DelegateCache[5] = new ICustomProperty_Delegates.SetIndexedValue_5(Do_Abi_SetIndexedValue_5)).ToPointer(), get_CanWrite_6 = Marshal.GetFunctionPointerForDelegate(DelegateCache[6] = new ICustomProperty_Delegates.get_CanWrite_6(Do_Abi_get_CanWrite_6)).ToPointer(), get_CanRead_7 = Marshal.GetFunctionPointerForDelegate(DelegateCache[7] = new ICustomProperty_Delegates.get_CanRead_7(Do_Abi_get_CanRead_7)).ToPointer(), -#else - get_Type_0 = (delegate*)&Do_Abi_get_Type_0, - get_Name_1 = (delegate*)&Do_Abi_get_Name_1, - GetValue_2 = (delegate*)&Do_Abi_GetValue_2, - SetValue_3 = (delegate*)&Do_Abi_SetValue_3, - GetIndexedValue_4 = (delegate*)&Do_Abi_GetIndexedValue_4, - SetIndexedValue_5 = (delegate*)&Do_Abi_SetIndexedValue_5, - get_CanWrite_6 = (delegate*)&Do_Abi_get_CanWrite_6, - get_CanRead_7 = (delegate*)&Do_Abi_get_CanRead_7 -#endif + }; var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 8); Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_GetValue_2(IntPtr thisPtr, IntPtr target, IntPtr* result) { object __result = default; @@ -98,9 +87,7 @@ private static unsafe int Do_Abi_GetValue_2(IntPtr thisPtr, IntPtr target, IntPt } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_SetValue_3(IntPtr thisPtr, IntPtr target, IntPtr value) { @@ -116,9 +103,7 @@ private static unsafe int Do_Abi_SetValue_3(IntPtr thisPtr, IntPtr target, IntPt } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_GetIndexedValue_4(IntPtr thisPtr, IntPtr target, IntPtr index, IntPtr* result) { object __result = default; @@ -136,9 +121,7 @@ private static unsafe int Do_Abi_GetIndexedValue_4(IntPtr thisPtr, IntPtr target } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_SetIndexedValue_5(IntPtr thisPtr, IntPtr target, IntPtr value, IntPtr index) { @@ -154,9 +137,7 @@ private static unsafe int Do_Abi_SetIndexedValue_5(IntPtr thisPtr, IntPtr target } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_get_CanRead_7(IntPtr thisPtr, byte* value) { bool __value = default; @@ -173,9 +154,7 @@ private static unsafe int Do_Abi_get_CanRead_7(IntPtr thisPtr, byte* value) } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_get_CanWrite_6(IntPtr thisPtr, byte* value) { bool __value = default; @@ -192,9 +171,7 @@ private static unsafe int Do_Abi_get_CanWrite_6(IntPtr thisPtr, byte* value) } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_get_Name_1(IntPtr thisPtr, IntPtr* value) { string __value = default; @@ -212,9 +189,7 @@ private static unsafe int Do_Abi_get_Name_1(IntPtr thisPtr, IntPtr* value) } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_get_Type_0(IntPtr thisPtr, global::ABI.System.Type* value) { global::System.Type __value = default; @@ -295,34 +270,27 @@ internal unsafe struct ManagedCustomPropertyProviderVftbl private static readonly ManagedCustomPropertyProviderVftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 + private static readonly Delegate[] DelegateCache = new Delegate[4]; -#endif + static unsafe ManagedCustomPropertyProviderVftbl() { AbiToProjectionVftable = new ManagedCustomPropertyProviderVftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 + GetCustomProperty_0 = Marshal.GetFunctionPointerForDelegate(new ICustomPropertyProvider_Delegates.GetCustomProperty_0(Do_Abi_GetCustomProperty_0)).ToPointer(), GetIndexedProperty_1 = Marshal.GetFunctionPointerForDelegate(new ICustomPropertyProvider_Delegates.GetIndexedProperty_1(Do_Abi_GetIndexedProperty_1)).ToPointer(), GetStringRepresentation_2 = Marshal.GetFunctionPointerForDelegate(new ICustomPropertyProvider_Delegates.GetStringRepresentation_2(Do_Abi_GetStringRepresentation_2)).ToPointer(), get_Type_3 = Marshal.GetFunctionPointerForDelegate(new ICustomPropertyProvider_Delegates.get_Type_3(Do_Abi_get_Type_3)).ToPointer(), -#else - GetCustomProperty_0 = (delegate*)&Do_Abi_GetCustomProperty_0, - GetIndexedProperty_1 = (delegate*)&Do_Abi_GetIndexedProperty_1, - GetStringRepresentation_2 = (delegate*)&Do_Abi_GetStringRepresentation_2, - get_Type_3 = (delegate*)&Do_Abi_get_Type_3 -#endif + }; var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(ManagedCustomPropertyProviderVftbl), Marshal.SizeOf() + sizeof(IntPtr) * 4); Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_GetCustomProperty_0(IntPtr thisPtr, IntPtr name, IntPtr* result) { global::Microsoft.UI.Xaml.Data.ICustomProperty __result = default; @@ -349,9 +317,7 @@ private static unsafe int Do_Abi_GetCustomProperty_0(IntPtr thisPtr, IntPtr name } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_GetIndexedProperty_1(IntPtr thisPtr, IntPtr name, global::ABI.System.Type type, IntPtr* result) { global::Microsoft.UI.Xaml.Data.ICustomProperty __result = default; @@ -382,9 +348,7 @@ private static unsafe int Do_Abi_GetIndexedProperty_1(IntPtr thisPtr, IntPtr nam } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_GetStringRepresentation_2(IntPtr thisPtr, IntPtr* result) { string __result = default; @@ -400,9 +364,7 @@ private static unsafe int Do_Abi_GetStringRepresentation_2(IntPtr thisPtr, IntPt } return 0; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_get_Type_3(IntPtr thisPtr, global::ABI.System.Type* value) { global::System.Type __value = default; diff --git a/WinRT.Runtime/Projections/IDictionary.net5.cs b/WinRT.Runtime/Projections/IDictionary.net5.cs new file mode 100644 index 000000000..ec941b1c8 --- /dev/null +++ b/WinRT.Runtime/Projections/IDictionary.net5.cs @@ -0,0 +1,840 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; +using System.Diagnostics; + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Windows.Foundation.Collections +{ + [Guid("3C2925FE-8519-45C1-AA79-197B6718C1C1")] + interface IMap : IIterable> + { + V Lookup(K key); + bool HasKey(K key); + IMapView GetView(); + bool Insert(K key, V value); + void _Remove(K key); + void Clear(); + uint Size { get; } + } +} + +namespace ABI.System.Collections.Generic +{ + using global::System; + using global::System.Runtime.CompilerServices; + + [DynamicInterfaceCastableImplementation] + [Guid("3C2925FE-8519-45C1-AA79-197B6718C1C1")] + interface IDictionary : global::System.Collections.Generic.IDictionary, global::Windows.Foundation.Collections.IMap + { + public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IDictionary obj) => + obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IDictionary))); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static global::System.Collections.Generic.IDictionary FromAbi(IntPtr thisPtr) => + thisPtr == IntPtr.Zero ? null : (global::System.Collections.Generic.IDictionary)(object)new IInspectable(ObjRefFromAbi(thisPtr)); + + public static IntPtr FromManaged(global::System.Collections.Generic.IDictionary value) => + (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); + + public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IDictionary)); + + public class FromAbiHelper : global::System.Collections.Generic.IDictionary + { + private readonly global::Windows.Foundation.Collections.IMap _map; + + public FromAbiHelper(global::Windows.Foundation.Collections.IMap map) + { + _map = map; + } + + public int Count + { + get + { + uint size = _map.Size; + + if (((uint)int.MaxValue) < size) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingDictionaryTooLarge); + } + + return (int)size; + } + } + + public bool IsReadOnly { get => false; } + + public void Add(global::System.Collections.Generic.KeyValuePair item) + { + _map.Insert(item.Key, item.Value); + } + + public void Clear() + { + _map.Clear(); + } + + public bool Contains(global::System.Collections.Generic.KeyValuePair item) + { + bool hasKey = _map.HasKey(item.Key); + if (!hasKey) + return false; + // todo: toctou + V value = _map.Lookup(item.Key); + return EqualityComparer.Default.Equals(value, item.Value); + } + + public void CopyTo(global::System.Collections.Generic.KeyValuePair[] array, int arrayIndex) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + + if (arrayIndex < 0) + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); + + if (array.Length <= arrayIndex && Count > 0) + throw new ArgumentException(ErrorStrings.Argument_IndexOutOfArrayBounds); + + if (array.Length - arrayIndex < Count) + throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); + + foreach (global::System.Collections.Generic.KeyValuePair mapping in this) + { + array[arrayIndex++] = mapping; + } + } + + public bool Remove(global::System.Collections.Generic.KeyValuePair item) + { + _map._Remove(item.Key); + return true; + } + + public V this[K key] { get => Indexer_Get(key); set => Indexer_Set(key, value); } + + private V Indexer_Get(K key) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + return Lookup(_map, key); + } + private void Indexer_Set(K key, V value) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + Insert(_map, key, value); + } + + public ICollection Keys { get => new DictionaryKeyCollection(this); } + + public ICollection Values { get => new DictionaryValueCollection(this); } + + public bool ContainsKey(K key) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + return _map.HasKey(key); + } + + public void Add(K key, V value) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + + if (ContainsKey(key)) + throw new ArgumentException(ErrorStrings.Argument_AddingDuplicate); + + Insert((this as global::Windows.Foundation.Collections.IMap), key, value); + } + + public bool Remove(K key) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + + if (!_map.HasKey(key)) + return false; + + try + { + _map._Remove(key); + return true; + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + return false; + + throw; + } + } + + public bool TryGetValue(K key, out V value) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + + if (!_map.HasKey(key)) + { + value = default!; + return false; + } + + try + { + value = Lookup((this as global::Windows.Foundation.Collections.IMap), key); + return true; + } + catch (KeyNotFoundException) + { + value = default!; + return false; + } + } + + private static V Lookup(global::Windows.Foundation.Collections.IMap _this, K key) + { + Debug.Assert(null != key); + + try + { + return _this.Lookup(key); + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new KeyNotFoundException(ErrorStrings.Arg_KeyNotFound); + throw; + } + } + + private static bool Insert(global::Windows.Foundation.Collections.IMap _this, K key, V value) + { + Debug.Assert(null != key); + + bool replaced = _this.Insert(key, value); + return replaced; + } + + public global::System.Collections.Generic.IEnumerator> GetEnumerator() => ((global::System.Collections.Generic.IEnumerable>)(IWinRTObject)_map).GetEnumerator(); + + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + + private sealed class DictionaryKeyCollection : global::System.Collections.Generic.ICollection + { + private readonly global::System.Collections.Generic.IDictionary dictionary; + + public DictionaryKeyCollection(global::System.Collections.Generic.IDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + } + + public void CopyTo(K[] array, int index) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + if (array.Length <= index && this.Count > 0) + throw new ArgumentException(ErrorStrings.Arg_IndexOutOfRangeException); + if (array.Length - index < dictionary.Count) + throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); + + int i = index; + foreach (global::System.Collections.Generic.KeyValuePair mapping in dictionary) + { + array[i++] = mapping.Key; + } + } + + public int Count => dictionary.Count; + + public bool IsReadOnly => true; + + void ICollection.Add(K item) + { + throw new NotSupportedException(ErrorStrings.NotSupported_KeyCollectionSet); + } + + void ICollection.Clear() + { + throw new NotSupportedException(ErrorStrings.NotSupported_KeyCollectionSet); + } + + public bool Contains(K item) + { + return dictionary.ContainsKey(item); + } + + bool ICollection.Remove(K item) + { + throw new NotSupportedException(ErrorStrings.NotSupported_KeyCollectionSet); + } + + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + + public global::System.Collections.Generic.IEnumerator GetEnumerator() => + new DictionaryKeyEnumerator(dictionary); + + private sealed class DictionaryKeyEnumerator : global::System.Collections.Generic.IEnumerator + { + private readonly global::System.Collections.Generic.IDictionary dictionary; + private global::System.Collections.Generic.IEnumerator> enumeration; + + public DictionaryKeyEnumerator(global::System.Collections.Generic.IDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + enumeration = dictionary.GetEnumerator(); + } + + public void Dispose() + { + enumeration.Dispose(); + } + + public bool MoveNext() + { + return enumeration.MoveNext(); + } + + object IEnumerator.Current => Current; + + public K Current => enumeration.Current.Key; + + public void Reset() + { + enumeration = dictionary.GetEnumerator(); + } + } + } + + private sealed class DictionaryValueCollection : global::System.Collections.Generic.ICollection + { + private readonly global::System.Collections.Generic.IDictionary dictionary; + + public DictionaryValueCollection(global::System.Collections.Generic.IDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + } + + public void CopyTo(V[] array, int index) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + if (array.Length <= index && this.Count > 0) + throw new ArgumentException(ErrorStrings.Arg_IndexOutOfRangeException); + if (array.Length - index < dictionary.Count) + throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); + + int i = index; + foreach (global::System.Collections.Generic.KeyValuePair mapping in dictionary) + { + array[i++] = mapping.Value; + } + } + + public int Count => dictionary.Count; + + public bool IsReadOnly => true; + + void ICollection.Add(V item) + { + throw new NotSupportedException(ErrorStrings.NotSupported_ValueCollectionSet); + } + + void ICollection.Clear() + { + throw new NotSupportedException(ErrorStrings.NotSupported_ValueCollectionSet); + } + + public bool Contains(V item) + { + EqualityComparer comparer = EqualityComparer.Default; + foreach (V value in this) + if (comparer.Equals(item, value)) + return true; + return false; + } + + bool ICollection.Remove(V item) + { + throw new NotSupportedException(ErrorStrings.NotSupported_ValueCollectionSet); + } + + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + + public global::System.Collections.Generic.IEnumerator GetEnumerator() + { + return new DictionaryValueEnumerator(dictionary); + } + + private sealed class DictionaryValueEnumerator : global::System.Collections.Generic.IEnumerator + { + private readonly global::System.Collections.Generic.IDictionary dictionary; + private global::System.Collections.Generic.IEnumerator> enumeration; + + public DictionaryValueEnumerator(global::System.Collections.Generic.IDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + enumeration = dictionary.GetEnumerator(); + } + + void IDisposable.Dispose() + { + enumeration.Dispose(); + } + + public bool MoveNext() + { + return enumeration.MoveNext(); + } + + object IEnumerator.Current => Current; + + public V Current => enumeration.Current.Value; + + public void Reset() + { + enumeration = dictionary.GetEnumerator(); + } + } + } + } + + public class ToAbiHelper : global::Windows.Foundation.Collections.IMap + { + private readonly global::System.Collections.Generic.IDictionary _dictionary; + + public ToAbiHelper(global::System.Collections.Generic.IDictionary dictionary) => _dictionary = dictionary; + + global::Windows.Foundation.Collections.IIterator> global::Windows.Foundation.Collections.IIterable>.First() => + new IEnumerator>.ToAbiHelper( + new KeyValuePair.Enumerator(_dictionary.GetEnumerator())); + + public V Lookup(K key) + { + V value; + bool keyFound = _dictionary.TryGetValue(key, out value); + + if (!keyFound) + { + Debug.Assert(key != null); + Exception e = new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + + return value; + } + + public uint Size { get => (uint)_dictionary.Count; } + + public bool HasKey(K key) => _dictionary.ContainsKey(key); + + global::Windows.Foundation.Collections.IMapView global::Windows.Foundation.Collections.IMap.GetView() + { + if (!(_dictionary is global::System.Collections.Generic.IReadOnlyDictionary roDictionary)) + { + roDictionary = new ReadOnlyDictionary(_dictionary); + } + return new IReadOnlyDictionary.ToAbiHelper(roDictionary); + } + + public bool Insert(K key, V value) + { + bool replacing = _dictionary.ContainsKey(key); + _dictionary[key] = value; + return replacing; + } + + public void _Remove(K key) + { + bool removed = _dictionary.Remove(key); + + if (!removed) + { + Debug.Assert(key != null); + Exception e = new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + } + + public void Clear() => _dictionary.Clear(); + } + + [Guid("3C2925FE-8519-45C1-AA79-197B6718C1C1")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate Lookup_0; + internal _get_PropertyAsUInt32 get_Size_1; + public global::System.Delegate HasKey_2; + public IDictionary_Delegates.GetView_3 GetView_3; + public global::System.Delegate Insert_4; + public global::System.Delegate Remove_5; + public IDictionary_Delegates.Clear_6 Clear_6; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IDictionary)); + private static readonly Type Lookup_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, Marshaler.AbiType.MakeByRefType(), typeof(int) }); + private static readonly Type HasKey_2_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(byte).MakeByRefType(), typeof(int) }); + private static readonly Type Insert_4_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, Marshaler.AbiType, typeof(byte).MakeByRefType(), typeof(int) }); + private static readonly Type Remove_5_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + Lookup_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], Lookup_0_Type); + get_Size_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsUInt32>(vftbl[7]); + HasKey_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8], HasKey_2_Type); + GetView_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9]); + Insert_4 = Marshal.GetDelegateForFunctionPointer(vftbl[10], Insert_4_Type); + Remove_5 = Marshal.GetDelegateForFunctionPointer(vftbl[11], Remove_5_Type); + Clear_6 = Marshal.GetDelegateForFunctionPointer(vftbl[12]); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + Lookup_0 = global::System.Delegate.CreateDelegate(Lookup_0_Type, typeof(Vftbl).GetMethod("Do_Abi_Lookup_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType, Marshaler.AbiType)), + get_Size_1 = Do_Abi_get_Size_1, + HasKey_2 = global::System.Delegate.CreateDelegate(HasKey_2_Type, typeof(Vftbl).GetMethod("Do_Abi_HasKey_2", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + GetView_3 = Do_Abi_GetView_3, + Insert_4 = global::System.Delegate.CreateDelegate(Insert_4_Type, typeof(Vftbl).GetMethod("Do_Abi_Insert_4", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType, Marshaler.AbiType)), + Remove_5 = global::System.Delegate.CreateDelegate(Remove_5_Type, typeof(Vftbl).GetMethod("Do_Abi_Remove_5", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + Clear_6 = Do_Abi_Clear_6 + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 7); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Lookup_0); + nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Size_1); + nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.HasKey_2); + nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetView_3); + nativeVftbl[10] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Insert_4); + nativeVftbl[11] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Remove_5); + nativeVftbl[12] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Clear_6); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable, ToAbiHelper> _adapterTable = + new ConditionalWeakTable, ToAbiHelper>(); + + private static global::Windows.Foundation.Collections.IMap FindAdapter(IntPtr thisPtr) + { + var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); + return _adapterTable.GetValue(__this, (dictionary) => new ToAbiHelper(dictionary)); + } + + private static unsafe int Do_Abi_Lookup_0(void* thisPtr, KAbi key, out VAbi __return_value__) + { + V ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Lookup(Marshaler.FromAbi(key)); + __return_value__ = (VAbi)Marshaler.FromManaged(____return_value__); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_HasKey_2(void* thisPtr, KAbi key, out byte __return_value__) + { + bool ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).HasKey(Marshaler.FromAbi(key)); + __return_value__ = (byte)(____return_value__ ? 1 : 0); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_GetView_3(IntPtr thisPtr, out IntPtr __return_value__) + { + global::Windows.Foundation.Collections.IMapView ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).GetView(); + __return_value__ = MarshalInterface>.FromManaged(____return_value__); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_Insert_4(void* thisPtr, KAbi key, VAbi value, out byte __return_value__) + { + bool ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Insert(Marshaler.FromAbi(key), Marshaler.FromAbi(value)); + __return_value__ = (byte)(____return_value__ ? 1 : 0); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_Remove_5(void* thisPtr, KAbi key) + { + + + try + { + FindAdapter(new IntPtr(thisPtr))._Remove(Marshaler.FromAbi(key)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_Clear_6(IntPtr thisPtr) + { + + + try + { + FindAdapter(thisPtr).Clear(); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).Size; __return_value__ = ____return_value__; + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + public static Guid PIID = Vftbl.PIID; + + unsafe V global::Windows.Foundation.Collections.IMap.Lookup(K key) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IDictionary).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + object __key = default; + var __params = new object[] { ThisPtr, null, null }; + try + { + __key = Marshaler.CreateMarshaler(key); + __params[1] = Marshaler.GetAbi(__key); + _obj.Vftbl.Lookup_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[2]); + } + finally + { + Marshaler.DisposeMarshaler(__key); + Marshaler.DisposeAbi(__params[2]); + } + } + + unsafe bool global::Windows.Foundation.Collections.IMap.HasKey(K key) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IDictionary).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + object __key = default; + var __params = new object[] { ThisPtr, null, null }; + try + { + __key = Marshaler.CreateMarshaler(key); + __params[1] = Marshaler.GetAbi(__key); + _obj.Vftbl.HasKey_2.DynamicInvokeAbi(__params); + return (byte)__params[2] != 0; + } + finally + { + Marshaler.DisposeMarshaler(__key); + } + } + + unsafe global::Windows.Foundation.Collections.IMapView global::Windows.Foundation.Collections.IMap.GetView() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IDictionary).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetView_3(ThisPtr, out __retval)); + return MarshalInterface>.FromAbi(__retval); + } + finally + { + MarshalInterface>.DisposeAbi(__retval); + } + } + + unsafe bool global::Windows.Foundation.Collections.IMap.Insert(K key, V value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IDictionary).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + object __key = default; + object __value = default; + var __params = new object[] { ThisPtr, null, null, null }; + try + { + __key = Marshaler.CreateMarshaler(key); + __params[1] = Marshaler.GetAbi(__key); + __value = Marshaler.CreateMarshaler(value); + __params[2] = Marshaler.GetAbi(__value); + _obj.Vftbl.Insert_4.DynamicInvokeAbi(__params); + return (byte)__params[3] != 0; + } + finally + { + Marshaler.DisposeMarshaler(__key); + Marshaler.DisposeMarshaler(__value); + } + } + + unsafe void global::Windows.Foundation.Collections.IMap._Remove(K key) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IDictionary).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + object __key = default; + var __params = new object[] { ThisPtr, null }; + try + { + __key = Marshaler.CreateMarshaler(key); + __params[1] = Marshaler.GetAbi(__key); + _obj.Vftbl.Remove_5.DynamicInvokeAbi(__params); + } + finally + { + Marshaler.DisposeMarshaler(__key); + } + } + + unsafe void global::System.Collections.Generic.ICollection>.Clear() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IDictionary).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Clear_6(ThisPtr)); + } + + unsafe uint global::Windows.Foundation.Collections.IMap.Size + { + get + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IDictionary).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + uint __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, out __retval)); + return __retval; + } + } + + static FromAbiHelper _FromMap(IWinRTObject obj) { + return (FromAbiHelper)obj.GetOrCreateTypeHelperData(typeof(global::System.Collections.Generic.IDictionary).TypeHandle, + () => new FromAbiHelper((global::Windows.Foundation.Collections.IMap)(IWinRTObject)obj)); + } + + ICollection global::System.Collections.Generic.IDictionary.Keys => _FromMap((IWinRTObject)this).Keys; + ICollection global::System.Collections.Generic.IDictionary.Values => _FromMap((IWinRTObject)this).Values; + int global::System.Collections.Generic.ICollection>.Count => _FromMap((IWinRTObject)this).Count; + bool global::System.Collections.Generic.ICollection>.IsReadOnly => _FromMap((IWinRTObject)this).IsReadOnly; + V global::System.Collections.Generic.IDictionary.this[K key] { get => _FromMap((IWinRTObject)this)[key]; set => _FromMap((IWinRTObject)this)[key] = value; } + void global::System.Collections.Generic.IDictionary.Add(K key, V value) => _FromMap((IWinRTObject)this).Add(key, value); + bool global::System.Collections.Generic.IDictionary.ContainsKey(K key) => _FromMap((IWinRTObject)this).ContainsKey(key); + bool global::System.Collections.Generic.IDictionary.Remove(K key) => _FromMap((IWinRTObject)this).Remove(key); + bool global::System.Collections.Generic.IDictionary.TryGetValue(K key, out V value) => _FromMap((IWinRTObject)this).TryGetValue(key, out value); + void global::System.Collections.Generic.ICollection>.Add(global::System.Collections.Generic.KeyValuePair item) => _FromMap((IWinRTObject)this).Add(item); + bool global::System.Collections.Generic.ICollection>.Contains(global::System.Collections.Generic.KeyValuePair item) => _FromMap((IWinRTObject)this).Contains(item); + void global::System.Collections.Generic.ICollection>.CopyTo(global::System.Collections.Generic.KeyValuePair[] array, int arrayIndex) => _FromMap((IWinRTObject)this).CopyTo(array, arrayIndex); + bool global::System.Collections.Generic.ICollection>.Remove(global::System.Collections.Generic.KeyValuePair item) => _FromMap((IWinRTObject)this).Remove(item); + global::System.Collections.Generic.IEnumerator> global::System.Collections.Generic.IEnumerable>.GetEnumerator() => _FromMap((IWinRTObject)this).GetEnumerator(); + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + + public 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/WinRT.Runtime/Projections/IDictionary.cs b/WinRT.Runtime/Projections/IDictionary.netstandard2.0.cs similarity index 97% rename from WinRT.Runtime/Projections/IDictionary.cs rename to WinRT.Runtime/Projections/IDictionary.netstandard2.0.cs index d2907bbe1..5db54af59 100644 --- a/WinRT.Runtime/Projections/IDictionary.cs +++ b/WinRT.Runtime/Projections/IDictionary.netstandard2.0.cs @@ -1,842 +1,842 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.InteropServices; -using WinRT; -using WinRT.Interop; -using System.Diagnostics; - -#pragma warning disable 0169 // warning CS0169: The field '...' is never used -#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to - -namespace Windows.Foundation.Collections -{ - [Guid("3C2925FE-8519-45C1-AA79-197B6718C1C1")] - interface IMap : IIterable> - { - V Lookup(K key); - bool HasKey(K key); - IMapView GetView(); - bool Insert(K key, V value); - void _Remove(K key); - void Clear(); - uint Size { get; } - } -} - -namespace ABI.System.Collections.Generic -{ - using global::System; - using global::System.Runtime.CompilerServices; - - [Guid("3C2925FE-8519-45C1-AA79-197B6718C1C1")] - public 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))); - - public static IntPtr GetAbi(IObjectReference objRef) => - objRef?.ThisPtr ?? IntPtr.Zero; - - public static global::System.Collections.Generic.IDictionary FromAbi(IntPtr thisPtr) => - thisPtr == IntPtr.Zero ? null : new IDictionary(ObjRefFromAbi(thisPtr)); - - public static IntPtr FromManaged(global::System.Collections.Generic.IDictionary value) => - (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); - - public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); - - public static void DisposeAbi(IntPtr abi) => - MarshalInterfaceHelper>.DisposeAbi(abi); - - public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IDictionary)); - - public class FromAbiHelper : global::System.Collections.Generic.IDictionary - { - private readonly global::ABI.System.Collections.Generic.IDictionary _map; - private readonly global::ABI.System.Collections.Generic.IEnumerable> _enumerable; - - public FromAbiHelper(IObjectReference obj) : - this(new global::ABI.System.Collections.Generic.IDictionary(obj)) - { - } - - public FromAbiHelper(global::ABI.System.Collections.Generic.IDictionary map) - { - _map = map; - _enumerable = new ABI.System.Collections.Generic.IEnumerable>(map.ObjRef); - } - - public int Count - { - get - { - uint size = _map.Size; - - if (((uint)int.MaxValue) < size) - { - throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingDictionaryTooLarge); - } - - return (int)size; - } - } - - public bool IsReadOnly { get => false; } - - public void Add(global::System.Collections.Generic.KeyValuePair item) - { - _map.Insert(item.Key, item.Value); - } - - public void Clear() - { - _map.Clear(); - } - - public bool Contains(global::System.Collections.Generic.KeyValuePair item) - { - bool hasKey = _map.HasKey(item.Key); - if (!hasKey) - return false; - // todo: toctou - V value = _map.Lookup(item.Key); - return EqualityComparer.Default.Equals(value, item.Value); - } - - public void CopyTo(global::System.Collections.Generic.KeyValuePair[] array, int arrayIndex) - { - if (array == null) - throw new ArgumentNullException(nameof(array)); - - if (arrayIndex < 0) - throw new ArgumentOutOfRangeException(nameof(arrayIndex)); - - if (array.Length <= arrayIndex && Count > 0) - throw new ArgumentException(ErrorStrings.Argument_IndexOutOfArrayBounds); - - if (array.Length - arrayIndex < Count) - throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); - - foreach (global::System.Collections.Generic.KeyValuePair mapping in this) - { - array[arrayIndex++] = mapping; - } - } - - public bool Remove(global::System.Collections.Generic.KeyValuePair item) - { - _map._Remove(item.Key); - return true; - } - - public V this[K key] { get => Indexer_Get(key); set => Indexer_Set(key, value); } - - private V Indexer_Get(K key) - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - return Lookup(_map, key); - } - private void Indexer_Set(K key, V value) - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - Insert(_map, key, value); - } - - public ICollection Keys { get => new DictionaryKeyCollection(this); } - - public ICollection Values { get => new DictionaryValueCollection(this); } - - public bool ContainsKey(K key) - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - return _map.HasKey(key); - } - - public void Add(K key, V value) - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - if (ContainsKey(key)) - throw new ArgumentException(ErrorStrings.Argument_AddingDuplicate); - - Insert(_map, key, value); - } - - public bool Remove(K key) - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - if (!_map.HasKey(key)) - return false; - - try - { - _map._Remove(key); - return true; - } - catch (Exception ex) - { - if (ExceptionHelpers.E_BOUNDS == ex.HResult) - return false; - - throw; - } - } - - public bool TryGetValue(K key, out V value) - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - if (!_map.HasKey(key)) - { - value = default!; - return false; - } - - try - { - value = Lookup(_map, key); - return true; - } - catch (KeyNotFoundException) - { - value = default!; - return false; - } - } - - private static V Lookup(IDictionary _this, K key) - { - Debug.Assert(null != key); - - try - { - return _this.Lookup(key); - } - catch (Exception ex) - { - if (ExceptionHelpers.E_BOUNDS == ex.HResult) - throw new KeyNotFoundException(ErrorStrings.Arg_KeyNotFound); - throw; - } - } - - private static bool Insert(IDictionary _this, K key, V value) - { - Debug.Assert(null != key); - - bool replaced = _this.Insert(key, value); - return replaced; - } - - public global::System.Collections.Generic.IEnumerator> GetEnumerator() => _enumerable.GetEnumerator(); - - global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - - private sealed class DictionaryKeyCollection : global::System.Collections.Generic.ICollection - { - private readonly global::System.Collections.Generic.IDictionary dictionary; - - public DictionaryKeyCollection(global::System.Collections.Generic.IDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - } - - public void CopyTo(K[] array, int index) - { - if (array == null) - throw new ArgumentNullException(nameof(array)); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - if (array.Length <= index && this.Count > 0) - throw new ArgumentException(ErrorStrings.Arg_IndexOutOfRangeException); - if (array.Length - index < dictionary.Count) - throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); - - int i = index; - foreach (global::System.Collections.Generic.KeyValuePair mapping in dictionary) - { - array[i++] = mapping.Key; - } - } - - public int Count => dictionary.Count; - - public bool IsReadOnly => true; - - void ICollection.Add(K item) - { - throw new NotSupportedException(ErrorStrings.NotSupported_KeyCollectionSet); - } - - void ICollection.Clear() - { - throw new NotSupportedException(ErrorStrings.NotSupported_KeyCollectionSet); - } - - public bool Contains(K item) - { - return dictionary.ContainsKey(item); - } - - bool ICollection.Remove(K item) - { - throw new NotSupportedException(ErrorStrings.NotSupported_KeyCollectionSet); - } - - global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - - public global::System.Collections.Generic.IEnumerator GetEnumerator() => - new DictionaryKeyEnumerator(dictionary); - - private sealed class DictionaryKeyEnumerator : global::System.Collections.Generic.IEnumerator - { - private readonly global::System.Collections.Generic.IDictionary dictionary; - private global::System.Collections.Generic.IEnumerator> enumeration; - - public DictionaryKeyEnumerator(global::System.Collections.Generic.IDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - enumeration = dictionary.GetEnumerator(); - } - - public void Dispose() - { - enumeration.Dispose(); - } - - public bool MoveNext() - { - return enumeration.MoveNext(); - } - - object IEnumerator.Current => Current; - - public K Current => enumeration.Current.Key; - - public void Reset() - { - enumeration = dictionary.GetEnumerator(); - } - } - } - - private sealed class DictionaryValueCollection : global::System.Collections.Generic.ICollection - { - private readonly global::System.Collections.Generic.IDictionary dictionary; - - public DictionaryValueCollection(global::System.Collections.Generic.IDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - } - - public void CopyTo(V[] array, int index) - { - if (array == null) - throw new ArgumentNullException(nameof(array)); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - if (array.Length <= index && this.Count > 0) - throw new ArgumentException(ErrorStrings.Arg_IndexOutOfRangeException); - if (array.Length - index < dictionary.Count) - throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); - - int i = index; - foreach (global::System.Collections.Generic.KeyValuePair mapping in dictionary) - { - array[i++] = mapping.Value; - } - } - - public int Count => dictionary.Count; - - public bool IsReadOnly => true; - - void ICollection.Add(V item) - { - throw new NotSupportedException(ErrorStrings.NotSupported_ValueCollectionSet); - } - - void ICollection.Clear() - { - throw new NotSupportedException(ErrorStrings.NotSupported_ValueCollectionSet); - } - - public bool Contains(V item) - { - EqualityComparer comparer = EqualityComparer.Default; - foreach (V value in this) - if (comparer.Equals(item, value)) - return true; - return false; - } - - bool ICollection.Remove(V item) - { - throw new NotSupportedException(ErrorStrings.NotSupported_ValueCollectionSet); - } - - IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - - public global::System.Collections.Generic.IEnumerator GetEnumerator() - { - return new DictionaryValueEnumerator(dictionary); - } - - private sealed class DictionaryValueEnumerator : global::System.Collections.Generic.IEnumerator - { - private readonly global::System.Collections.Generic.IDictionary dictionary; - private global::System.Collections.Generic.IEnumerator> enumeration; - - public DictionaryValueEnumerator(global::System.Collections.Generic.IDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - enumeration = dictionary.GetEnumerator(); - } - - void IDisposable.Dispose() - { - enumeration.Dispose(); - } - - public bool MoveNext() - { - return enumeration.MoveNext(); - } - - object IEnumerator.Current => Current; - - public V Current => enumeration.Current.Value; - - public void Reset() - { - enumeration = dictionary.GetEnumerator(); - } - } - } - } - - public class ToAbiHelper : global::Windows.Foundation.Collections.IMap - { - private readonly global::System.Collections.Generic.IDictionary _dictionary; - - public ToAbiHelper(global::System.Collections.Generic.IDictionary dictionary) => _dictionary = dictionary; - - global::Windows.Foundation.Collections.IIterator> global::Windows.Foundation.Collections.IIterable>.First() => - new IEnumerator>.ToAbiHelper( - new KeyValuePair.Enumerator(_dictionary.GetEnumerator())); - - public V Lookup(K key) - { - V value; - bool keyFound = _dictionary.TryGetValue(key, out value); - - if (!keyFound) - { - Debug.Assert(key != null); - Exception e = new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); - e.SetHResult(ExceptionHelpers.E_BOUNDS); - throw e; - } - - return value; - } - - public uint Size { get => (uint)_dictionary.Count; } - - public bool HasKey(K key) => _dictionary.ContainsKey(key); - - global::Windows.Foundation.Collections.IMapView global::Windows.Foundation.Collections.IMap.GetView() - { - if (!(_dictionary is global::System.Collections.Generic.IReadOnlyDictionary roDictionary)) - { - roDictionary = new ReadOnlyDictionary(_dictionary); - } - return new IReadOnlyDictionary.ToAbiHelper(roDictionary); - } - - public bool Insert(K key, V value) - { - bool replacing = _dictionary.ContainsKey(key); - _dictionary[key] = value; - return replacing; - } - - public void _Remove(K key) - { - bool removed = _dictionary.Remove(key); - - if (!removed) - { - Debug.Assert(key != null); - Exception e = new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); - e.SetHResult(ExceptionHelpers.E_BOUNDS); - throw e; - } - } - - public void Clear() => _dictionary.Clear(); - } - - [Guid("3C2925FE-8519-45C1-AA79-197B6718C1C1")] - public struct Vftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - public global::System.Delegate Lookup_0; - internal _get_PropertyAsUInt32 get_Size_1; - public global::System.Delegate HasKey_2; - public IDictionary_Delegates.GetView_3 GetView_3; - public global::System.Delegate Insert_4; - public global::System.Delegate Remove_5; - public IDictionary_Delegates.Clear_6 Clear_6; - public static Guid PIID = GuidGenerator.CreateIID(typeof(IDictionary)); - private static readonly Type Lookup_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, Marshaler.AbiType.MakeByRefType(), typeof(int) }); - private static readonly Type HasKey_2_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(byte).MakeByRefType(), typeof(int) }); - private static readonly Type Insert_4_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, Marshaler.AbiType, typeof(byte).MakeByRefType(), typeof(int) }); - private static readonly Type Remove_5_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(int) }); - - internal unsafe Vftbl(IntPtr thisPtr) - { - var vftblPtr = Marshal.PtrToStructure(thisPtr); - var vftbl = (IntPtr*)vftblPtr.Vftbl; - IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); - Lookup_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], Lookup_0_Type); - get_Size_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsUInt32>(vftbl[7]); - HasKey_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8], HasKey_2_Type); - GetView_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9]); - Insert_4 = Marshal.GetDelegateForFunctionPointer(vftbl[10], Insert_4_Type); - Remove_5 = Marshal.GetDelegateForFunctionPointer(vftbl[11], Remove_5_Type); - Clear_6 = Marshal.GetDelegateForFunctionPointer(vftbl[12]); - } - - private static readonly Vftbl AbiToProjectionVftable; - public static readonly IntPtr AbiToProjectionVftablePtr; - static unsafe Vftbl() - { - AbiToProjectionVftable = new Vftbl - { - IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, - Lookup_0 = global::System.Delegate.CreateDelegate(Lookup_0_Type, typeof(Vftbl).GetMethod("Do_Abi_Lookup_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType, Marshaler.AbiType)), - get_Size_1 = Do_Abi_get_Size_1, - HasKey_2 = global::System.Delegate.CreateDelegate(HasKey_2_Type, typeof(Vftbl).GetMethod("Do_Abi_HasKey_2", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), - GetView_3 = Do_Abi_GetView_3, - Insert_4 = global::System.Delegate.CreateDelegate(Insert_4_Type, typeof(Vftbl).GetMethod("Do_Abi_Insert_4", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType, Marshaler.AbiType)), - Remove_5 = global::System.Delegate.CreateDelegate(Remove_5_Type, typeof(Vftbl).GetMethod("Do_Abi_Remove_5", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), - Clear_6 = Do_Abi_Clear_6 - }; - var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 7); - Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); - nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Lookup_0); - nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Size_1); - nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.HasKey_2); - nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetView_3); - nativeVftbl[10] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Insert_4); - nativeVftbl[11] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Remove_5); - nativeVftbl[12] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Clear_6); - - AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; - } - - private static ConditionalWeakTable, ToAbiHelper> _adapterTable = - new ConditionalWeakTable, ToAbiHelper>(); - - private static global::Windows.Foundation.Collections.IMap FindAdapter(IntPtr thisPtr) - { - var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); - return _adapterTable.GetValue(__this, (dictionary) => new ToAbiHelper(dictionary)); - } - - private static unsafe int Do_Abi_Lookup_0(void* thisPtr, KAbi key, out VAbi __return_value__) - { - V ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Lookup(Marshaler.FromAbi(key)); - __return_value__ = (VAbi)Marshaler.FromManaged(____return_value__); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_HasKey_2(void* thisPtr, KAbi key, out byte __return_value__) - { - bool ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(new IntPtr(thisPtr)).HasKey(Marshaler.FromAbi(key)); - __return_value__ = (byte)(____return_value__ ? 1 : 0); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_GetView_3(IntPtr thisPtr, out IntPtr __return_value__) - { - global::Windows.Foundation.Collections.IMapView ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(thisPtr).GetView(); - __return_value__ = MarshalInterface>.FromManaged(____return_value__); - - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_Insert_4(void* thisPtr, KAbi key, VAbi value, out byte __return_value__) - { - bool ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Insert(Marshaler.FromAbi(key), Marshaler.FromAbi(value)); - __return_value__ = (byte)(____return_value__ ? 1 : 0); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_Remove_5(void* thisPtr, KAbi key) - { - - - try - { - FindAdapter(new IntPtr(thisPtr))._Remove(Marshaler.FromAbi(key)); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_Clear_6(IntPtr thisPtr) - { - - - try - { - FindAdapter(thisPtr).Clear(); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, out uint __return_value__) - { - uint ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(thisPtr).Size; __return_value__ = ____return_value__; - - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - } - public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) - { - if (thisPtr == IntPtr.Zero) - { - return null; - } - var vftblT = new Vftbl(thisPtr); - return ObjectReference.FromAbi(thisPtr, vftblT); - } - public static Guid PIID = Vftbl.PIID; - - public static implicit operator IDictionary(IObjectReference obj) => (obj != null) ? new IDictionary(obj) : null; - public static implicit operator IDictionary(ObjectReference obj) => (obj != null) ? new IDictionary(obj) : null; - protected readonly ObjectReference _obj; - public IObjectReference ObjRef { get => _obj; } - - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - public IDictionary(IObjectReference obj) : this(obj.As()) { } - public IDictionary(ObjectReference obj) - { - _obj = obj; - _FromMap = new FromAbiHelper(this); - } - FromAbiHelper _FromMap; - - public unsafe V Lookup(K key) - { - object __key = default; - var __params = new object[] { ThisPtr, null, null }; - try - { - __key = Marshaler.CreateMarshaler(key); - __params[1] = Marshaler.GetAbi(__key); - _obj.Vftbl.Lookup_0.DynamicInvokeAbi(__params); - return Marshaler.FromAbi(__params[2]); - } - finally - { - Marshaler.DisposeMarshaler(__key); - Marshaler.DisposeAbi(__params[2]); - } - } - - public unsafe bool HasKey(K key) - { - object __key = default; - var __params = new object[] { ThisPtr, null, null }; - try - { - __key = Marshaler.CreateMarshaler(key); - __params[1] = Marshaler.GetAbi(__key); - _obj.Vftbl.HasKey_2.DynamicInvokeAbi(__params); - return (byte)__params[2] != 0; - } - finally - { - Marshaler.DisposeMarshaler(__key); - } - } - - internal unsafe global::Windows.Foundation.Collections.IMapView GetView() - { - IntPtr __retval = default; - try - { - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetView_3(ThisPtr, out __retval)); - return MarshalInterface>.FromAbi(__retval); - } - finally - { - MarshalInterface>.DisposeAbi(__retval); - } - } - - public unsafe bool Insert(K key, V value) - { - object __key = default; - object __value = default; - var __params = new object[] { ThisPtr, null, null, null }; - try - { - __key = Marshaler.CreateMarshaler(key); - __params[1] = Marshaler.GetAbi(__key); - __value = Marshaler.CreateMarshaler(value); - __params[2] = Marshaler.GetAbi(__value); - _obj.Vftbl.Insert_4.DynamicInvokeAbi(__params); - return (byte)__params[3] != 0; - } - finally - { - Marshaler.DisposeMarshaler(__key); - Marshaler.DisposeMarshaler(__value); - } - } - - public unsafe void _Remove(K key) - { - object __key = default; - var __params = new object[] { ThisPtr, null }; - try - { - __key = Marshaler.CreateMarshaler(key); - __params[1] = Marshaler.GetAbi(__key); - _obj.Vftbl.Remove_5.DynamicInvokeAbi(__params); - } - finally - { - Marshaler.DisposeMarshaler(__key); - } - } - - public unsafe void Clear() - { - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Clear_6(ThisPtr)); - } - - public unsafe uint Size - { - get - { - uint __retval = default; - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, out __retval)); - return __retval; - } - } - - public ICollection Keys => _FromMap.Keys; - public ICollection Values => _FromMap.Values; - public int Count => _FromMap.Count; - public bool IsReadOnly => _FromMap.IsReadOnly; - public V this[K key] { get => _FromMap[key]; set => _FromMap[key] = value; } - public void Add(K key, V value) => _FromMap.Add(key, value); - public bool ContainsKey(K key) => _FromMap.ContainsKey(key); - public bool Remove(K key) => _FromMap.Remove(key); - public bool TryGetValue(K key, out V value) => _FromMap.TryGetValue(key, out value); - public void Add(global::System.Collections.Generic.KeyValuePair item) => _FromMap.Add(item); - public bool Contains(global::System.Collections.Generic.KeyValuePair item) => _FromMap.Contains(item); - public void CopyTo(global::System.Collections.Generic.KeyValuePair[] array, int arrayIndex) => _FromMap.CopyTo(array, arrayIndex); - public bool Remove(global::System.Collections.Generic.KeyValuePair item) => _FromMap.Remove(item); - public global::System.Collections.Generic.IEnumerator> GetEnumerator() => _FromMap.GetEnumerator(); - IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - } - public static class IDictionary_Delegates - { - public unsafe delegate int GetView_3(IntPtr thisPtr, out IntPtr __return_value__); - public unsafe delegate int Clear_6(IntPtr thisPtr); - } -} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; +using System.Diagnostics; + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Windows.Foundation.Collections +{ + [Guid("3C2925FE-8519-45C1-AA79-197B6718C1C1")] + interface IMap : IIterable> + { + V Lookup(K key); + bool HasKey(K key); + IMapView GetView(); + bool Insert(K key, V value); + void _Remove(K key); + void Clear(); + uint Size { get; } + } +} + +namespace ABI.System.Collections.Generic +{ + using global::System; + using global::System.Runtime.CompilerServices; + + [Guid("3C2925FE-8519-45C1-AA79-197B6718C1C1")] + public 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))); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static global::System.Collections.Generic.IDictionary FromAbi(IntPtr thisPtr) => + thisPtr == IntPtr.Zero ? null : new IDictionary(ObjRefFromAbi(thisPtr)); + + public static IntPtr FromManaged(global::System.Collections.Generic.IDictionary value) => + (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); + + public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IDictionary)); + + public class FromAbiHelper : global::System.Collections.Generic.IDictionary + { + private readonly global::ABI.System.Collections.Generic.IDictionary _map; + private readonly global::ABI.System.Collections.Generic.IEnumerable> _enumerable; + + public FromAbiHelper(IObjectReference obj) : + this(new global::ABI.System.Collections.Generic.IDictionary(obj)) + { + } + + public FromAbiHelper(global::ABI.System.Collections.Generic.IDictionary map) + { + _map = map; + _enumerable = new ABI.System.Collections.Generic.IEnumerable>(map.ObjRef); + } + + public int Count + { + get + { + uint size = _map.Size; + + if (((uint)int.MaxValue) < size) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingDictionaryTooLarge); + } + + return (int)size; + } + } + + public bool IsReadOnly { get => false; } + + public void Add(global::System.Collections.Generic.KeyValuePair item) + { + _map.Insert(item.Key, item.Value); + } + + public void Clear() + { + _map.Clear(); + } + + public bool Contains(global::System.Collections.Generic.KeyValuePair item) + { + bool hasKey = _map.HasKey(item.Key); + if (!hasKey) + return false; + // todo: toctou + V value = _map.Lookup(item.Key); + return EqualityComparer.Default.Equals(value, item.Value); + } + + public void CopyTo(global::System.Collections.Generic.KeyValuePair[] array, int arrayIndex) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + + if (arrayIndex < 0) + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); + + if (array.Length <= arrayIndex && Count > 0) + throw new ArgumentException(ErrorStrings.Argument_IndexOutOfArrayBounds); + + if (array.Length - arrayIndex < Count) + throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); + + foreach (global::System.Collections.Generic.KeyValuePair mapping in this) + { + array[arrayIndex++] = mapping; + } + } + + public bool Remove(global::System.Collections.Generic.KeyValuePair item) + { + _map._Remove(item.Key); + return true; + } + + public V this[K key] { get => Indexer_Get(key); set => Indexer_Set(key, value); } + + private V Indexer_Get(K key) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + return Lookup(_map, key); + } + private void Indexer_Set(K key, V value) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + Insert(_map, key, value); + } + + public ICollection Keys { get => new DictionaryKeyCollection(this); } + + public ICollection Values { get => new DictionaryValueCollection(this); } + + public bool ContainsKey(K key) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + return _map.HasKey(key); + } + + public void Add(K key, V value) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + + if (ContainsKey(key)) + throw new ArgumentException(ErrorStrings.Argument_AddingDuplicate); + + Insert(_map, key, value); + } + + public bool Remove(K key) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + + if (!_map.HasKey(key)) + return false; + + try + { + _map._Remove(key); + return true; + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + return false; + + throw; + } + } + + public bool TryGetValue(K key, out V value) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + + if (!_map.HasKey(key)) + { + value = default!; + return false; + } + + try + { + value = Lookup(_map, key); + return true; + } + catch (KeyNotFoundException) + { + value = default!; + return false; + } + } + + private static V Lookup(IDictionary _this, K key) + { + Debug.Assert(null != key); + + try + { + return _this.Lookup(key); + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new KeyNotFoundException(ErrorStrings.Arg_KeyNotFound); + throw; + } + } + + private static bool Insert(IDictionary _this, K key, V value) + { + Debug.Assert(null != key); + + bool replaced = _this.Insert(key, value); + return replaced; + } + + public global::System.Collections.Generic.IEnumerator> GetEnumerator() => _enumerable.GetEnumerator(); + + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + + private sealed class DictionaryKeyCollection : global::System.Collections.Generic.ICollection + { + private readonly global::System.Collections.Generic.IDictionary dictionary; + + public DictionaryKeyCollection(global::System.Collections.Generic.IDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + } + + public void CopyTo(K[] array, int index) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + if (array.Length <= index && this.Count > 0) + throw new ArgumentException(ErrorStrings.Arg_IndexOutOfRangeException); + if (array.Length - index < dictionary.Count) + throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); + + int i = index; + foreach (global::System.Collections.Generic.KeyValuePair mapping in dictionary) + { + array[i++] = mapping.Key; + } + } + + public int Count => dictionary.Count; + + public bool IsReadOnly => true; + + void ICollection.Add(K item) + { + throw new NotSupportedException(ErrorStrings.NotSupported_KeyCollectionSet); + } + + void ICollection.Clear() + { + throw new NotSupportedException(ErrorStrings.NotSupported_KeyCollectionSet); + } + + public bool Contains(K item) + { + return dictionary.ContainsKey(item); + } + + bool ICollection.Remove(K item) + { + throw new NotSupportedException(ErrorStrings.NotSupported_KeyCollectionSet); + } + + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + + public global::System.Collections.Generic.IEnumerator GetEnumerator() => + new DictionaryKeyEnumerator(dictionary); + + private sealed class DictionaryKeyEnumerator : global::System.Collections.Generic.IEnumerator + { + private readonly global::System.Collections.Generic.IDictionary dictionary; + private global::System.Collections.Generic.IEnumerator> enumeration; + + public DictionaryKeyEnumerator(global::System.Collections.Generic.IDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + enumeration = dictionary.GetEnumerator(); + } + + public void Dispose() + { + enumeration.Dispose(); + } + + public bool MoveNext() + { + return enumeration.MoveNext(); + } + + object IEnumerator.Current => Current; + + public K Current => enumeration.Current.Key; + + public void Reset() + { + enumeration = dictionary.GetEnumerator(); + } + } + } + + private sealed class DictionaryValueCollection : global::System.Collections.Generic.ICollection + { + private readonly global::System.Collections.Generic.IDictionary dictionary; + + public DictionaryValueCollection(global::System.Collections.Generic.IDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + } + + public void CopyTo(V[] array, int index) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + if (array.Length <= index && this.Count > 0) + throw new ArgumentException(ErrorStrings.Arg_IndexOutOfRangeException); + if (array.Length - index < dictionary.Count) + throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); + + int i = index; + foreach (global::System.Collections.Generic.KeyValuePair mapping in dictionary) + { + array[i++] = mapping.Value; + } + } + + public int Count => dictionary.Count; + + public bool IsReadOnly => true; + + void ICollection.Add(V item) + { + throw new NotSupportedException(ErrorStrings.NotSupported_ValueCollectionSet); + } + + void ICollection.Clear() + { + throw new NotSupportedException(ErrorStrings.NotSupported_ValueCollectionSet); + } + + public bool Contains(V item) + { + EqualityComparer comparer = EqualityComparer.Default; + foreach (V value in this) + if (comparer.Equals(item, value)) + return true; + return false; + } + + bool ICollection.Remove(V item) + { + throw new NotSupportedException(ErrorStrings.NotSupported_ValueCollectionSet); + } + + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + + public global::System.Collections.Generic.IEnumerator GetEnumerator() + { + return new DictionaryValueEnumerator(dictionary); + } + + private sealed class DictionaryValueEnumerator : global::System.Collections.Generic.IEnumerator + { + private readonly global::System.Collections.Generic.IDictionary dictionary; + private global::System.Collections.Generic.IEnumerator> enumeration; + + public DictionaryValueEnumerator(global::System.Collections.Generic.IDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + enumeration = dictionary.GetEnumerator(); + } + + void IDisposable.Dispose() + { + enumeration.Dispose(); + } + + public bool MoveNext() + { + return enumeration.MoveNext(); + } + + object IEnumerator.Current => Current; + + public V Current => enumeration.Current.Value; + + public void Reset() + { + enumeration = dictionary.GetEnumerator(); + } + } + } + } + + public class ToAbiHelper : global::Windows.Foundation.Collections.IMap + { + private readonly global::System.Collections.Generic.IDictionary _dictionary; + + public ToAbiHelper(global::System.Collections.Generic.IDictionary dictionary) => _dictionary = dictionary; + + global::Windows.Foundation.Collections.IIterator> global::Windows.Foundation.Collections.IIterable>.First() => + new IEnumerator>.ToAbiHelper( + new KeyValuePair.Enumerator(_dictionary.GetEnumerator())); + + public V Lookup(K key) + { + V value; + bool keyFound = _dictionary.TryGetValue(key, out value); + + if (!keyFound) + { + Debug.Assert(key != null); + Exception e = new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + + return value; + } + + public uint Size { get => (uint)_dictionary.Count; } + + public bool HasKey(K key) => _dictionary.ContainsKey(key); + + global::Windows.Foundation.Collections.IMapView global::Windows.Foundation.Collections.IMap.GetView() + { + if (!(_dictionary is global::System.Collections.Generic.IReadOnlyDictionary roDictionary)) + { + roDictionary = new ReadOnlyDictionary(_dictionary); + } + return new IReadOnlyDictionary.ToAbiHelper(roDictionary); + } + + public bool Insert(K key, V value) + { + bool replacing = _dictionary.ContainsKey(key); + _dictionary[key] = value; + return replacing; + } + + public void _Remove(K key) + { + bool removed = _dictionary.Remove(key); + + if (!removed) + { + Debug.Assert(key != null); + Exception e = new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + } + + public void Clear() => _dictionary.Clear(); + } + + [Guid("3C2925FE-8519-45C1-AA79-197B6718C1C1")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate Lookup_0; + internal _get_PropertyAsUInt32 get_Size_1; + public global::System.Delegate HasKey_2; + public IDictionary_Delegates.GetView_3 GetView_3; + public global::System.Delegate Insert_4; + public global::System.Delegate Remove_5; + public IDictionary_Delegates.Clear_6 Clear_6; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IDictionary)); + private static readonly Type Lookup_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, Marshaler.AbiType.MakeByRefType(), typeof(int) }); + private static readonly Type HasKey_2_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(byte).MakeByRefType(), typeof(int) }); + private static readonly Type Insert_4_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, Marshaler.AbiType, typeof(byte).MakeByRefType(), typeof(int) }); + private static readonly Type Remove_5_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + Lookup_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], Lookup_0_Type); + get_Size_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsUInt32>(vftbl[7]); + HasKey_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8], HasKey_2_Type); + GetView_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9]); + Insert_4 = Marshal.GetDelegateForFunctionPointer(vftbl[10], Insert_4_Type); + Remove_5 = Marshal.GetDelegateForFunctionPointer(vftbl[11], Remove_5_Type); + Clear_6 = Marshal.GetDelegateForFunctionPointer(vftbl[12]); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + Lookup_0 = global::System.Delegate.CreateDelegate(Lookup_0_Type, typeof(Vftbl).GetMethod("Do_Abi_Lookup_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType, Marshaler.AbiType)), + get_Size_1 = Do_Abi_get_Size_1, + HasKey_2 = global::System.Delegate.CreateDelegate(HasKey_2_Type, typeof(Vftbl).GetMethod("Do_Abi_HasKey_2", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + GetView_3 = Do_Abi_GetView_3, + Insert_4 = global::System.Delegate.CreateDelegate(Insert_4_Type, typeof(Vftbl).GetMethod("Do_Abi_Insert_4", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType, Marshaler.AbiType)), + Remove_5 = global::System.Delegate.CreateDelegate(Remove_5_Type, typeof(Vftbl).GetMethod("Do_Abi_Remove_5", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + Clear_6 = Do_Abi_Clear_6 + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 7); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Lookup_0); + nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Size_1); + nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.HasKey_2); + nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetView_3); + nativeVftbl[10] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Insert_4); + nativeVftbl[11] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Remove_5); + nativeVftbl[12] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Clear_6); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable, ToAbiHelper> _adapterTable = + new ConditionalWeakTable, ToAbiHelper>(); + + private static global::Windows.Foundation.Collections.IMap FindAdapter(IntPtr thisPtr) + { + var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); + return _adapterTable.GetValue(__this, (dictionary) => new ToAbiHelper(dictionary)); + } + + private static unsafe int Do_Abi_Lookup_0(void* thisPtr, KAbi key, out VAbi __return_value__) + { + V ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Lookup(Marshaler.FromAbi(key)); + __return_value__ = (VAbi)Marshaler.FromManaged(____return_value__); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_HasKey_2(void* thisPtr, KAbi key, out byte __return_value__) + { + bool ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).HasKey(Marshaler.FromAbi(key)); + __return_value__ = (byte)(____return_value__ ? 1 : 0); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_GetView_3(IntPtr thisPtr, out IntPtr __return_value__) + { + global::Windows.Foundation.Collections.IMapView ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).GetView(); + __return_value__ = MarshalInterface>.FromManaged(____return_value__); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_Insert_4(void* thisPtr, KAbi key, VAbi value, out byte __return_value__) + { + bool ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Insert(Marshaler.FromAbi(key), Marshaler.FromAbi(value)); + __return_value__ = (byte)(____return_value__ ? 1 : 0); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_Remove_5(void* thisPtr, KAbi key) + { + + + try + { + FindAdapter(new IntPtr(thisPtr))._Remove(Marshaler.FromAbi(key)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_Clear_6(IntPtr thisPtr) + { + + + try + { + FindAdapter(thisPtr).Clear(); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).Size; __return_value__ = ____return_value__; + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + public static Guid PIID = Vftbl.PIID; + + public static implicit operator IDictionary(IObjectReference obj) => (obj != null) ? new IDictionary(obj) : null; + public static implicit operator IDictionary(ObjectReference obj) => (obj != null) ? new IDictionary(obj) : null; + protected readonly ObjectReference _obj; + public IObjectReference ObjRef { get => _obj; } + + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public IDictionary(IObjectReference obj) : this(obj.As()) { } + public IDictionary(ObjectReference obj) + { + _obj = obj; + _FromMap = new FromAbiHelper(this); + } + FromAbiHelper _FromMap; + + public unsafe V Lookup(K key) + { + object __key = default; + var __params = new object[] { ThisPtr, null, null }; + try + { + __key = Marshaler.CreateMarshaler(key); + __params[1] = Marshaler.GetAbi(__key); + _obj.Vftbl.Lookup_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[2]); + } + finally + { + Marshaler.DisposeMarshaler(__key); + Marshaler.DisposeAbi(__params[2]); + } + } + + public unsafe bool HasKey(K key) + { + object __key = default; + var __params = new object[] { ThisPtr, null, null }; + try + { + __key = Marshaler.CreateMarshaler(key); + __params[1] = Marshaler.GetAbi(__key); + _obj.Vftbl.HasKey_2.DynamicInvokeAbi(__params); + return (byte)__params[2] != 0; + } + finally + { + Marshaler.DisposeMarshaler(__key); + } + } + + internal unsafe global::Windows.Foundation.Collections.IMapView GetView() + { + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetView_3(ThisPtr, out __retval)); + return MarshalInterface>.FromAbi(__retval); + } + finally + { + MarshalInterface>.DisposeAbi(__retval); + } + } + + public unsafe bool Insert(K key, V value) + { + object __key = default; + object __value = default; + var __params = new object[] { ThisPtr, null, null, null }; + try + { + __key = Marshaler.CreateMarshaler(key); + __params[1] = Marshaler.GetAbi(__key); + __value = Marshaler.CreateMarshaler(value); + __params[2] = Marshaler.GetAbi(__value); + _obj.Vftbl.Insert_4.DynamicInvokeAbi(__params); + return (byte)__params[3] != 0; + } + finally + { + Marshaler.DisposeMarshaler(__key); + Marshaler.DisposeMarshaler(__value); + } + } + + public unsafe void _Remove(K key) + { + object __key = default; + var __params = new object[] { ThisPtr, null }; + try + { + __key = Marshaler.CreateMarshaler(key); + __params[1] = Marshaler.GetAbi(__key); + _obj.Vftbl.Remove_5.DynamicInvokeAbi(__params); + } + finally + { + Marshaler.DisposeMarshaler(__key); + } + } + + public unsafe void Clear() + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Clear_6(ThisPtr)); + } + + public unsafe uint Size + { + get + { + uint __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, out __retval)); + return __retval; + } + } + + public ICollection Keys => _FromMap.Keys; + public ICollection Values => _FromMap.Values; + public int Count => _FromMap.Count; + public bool IsReadOnly => _FromMap.IsReadOnly; + public V this[K key] { get => _FromMap[key]; set => _FromMap[key] = value; } + public void Add(K key, V value) => _FromMap.Add(key, value); + public bool ContainsKey(K key) => _FromMap.ContainsKey(key); + public bool Remove(K key) => _FromMap.Remove(key); + public bool TryGetValue(K key, out V value) => _FromMap.TryGetValue(key, out value); + public void Add(global::System.Collections.Generic.KeyValuePair item) => _FromMap.Add(item); + public bool Contains(global::System.Collections.Generic.KeyValuePair item) => _FromMap.Contains(item); + public void CopyTo(global::System.Collections.Generic.KeyValuePair[] array, int arrayIndex) => _FromMap.CopyTo(array, arrayIndex); + public bool Remove(global::System.Collections.Generic.KeyValuePair item) => _FromMap.Remove(item); + public global::System.Collections.Generic.IEnumerator> GetEnumerator() => _FromMap.GetEnumerator(); + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + public 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/WinRT.Runtime/Projections/IDisposable.net5.cs b/WinRT.Runtime/Projections/IDisposable.net5.cs new file mode 100644 index 000000000..86674ae25 --- /dev/null +++ b/WinRT.Runtime/Projections/IDisposable.net5.cs @@ -0,0 +1,69 @@ +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; + +namespace ABI.System +{ + [DynamicInterfaceCastableImplementation] + [EditorBrowsable(EditorBrowsableState.Never)] + [Guid("30D5A829-7FA4-4026-83BB-D75BAE4EA99E")] + public unsafe interface IDisposable : global::System.IDisposable + { + [Guid("30D5A829-7FA4-4026-83BB-D75BAE4EA99E")] + public struct Vftbl + { + private delegate int CloseDelegate(IntPtr thisPtr); + internal IInspectable.Vftbl IInspectableVftbl; + private void* _Close_0; + public delegate* stdcall Close_0 { get => (delegate* stdcall)_Close_0; set => _Close_0 = value; } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + _Close_0 = (delegate*)&Do_Abi_Close_0 + + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 1); + Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_Close_0(IntPtr thisPtr) + { + + + try + { + global::WinRT.ComWrappersSupport.FindObject(thisPtr).Dispose(); + + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + internal static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + unsafe void global::System.IDisposable.Dispose() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.IDisposable).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Close_0(ThisPtr)); + } + } +} diff --git a/WinRT.Runtime/Projections/IDisposable.cs b/WinRT.Runtime/Projections/IDisposable.netstandard2.0.cs similarity index 93% rename from WinRT.Runtime/Projections/IDisposable.cs rename to WinRT.Runtime/Projections/IDisposable.netstandard2.0.cs index 00656c2c3..3970e9359 100644 --- a/WinRT.Runtime/Projections/IDisposable.cs +++ b/WinRT.Runtime/Projections/IDisposable.netstandard2.0.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel; using System.Runtime.InteropServices; using WinRT; @@ -21,28 +21,24 @@ public struct Vftbl private static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 + private static CloseDelegate closeDelegate; -#endif + static unsafe Vftbl() { AbiToProjectionVftable = new Vftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 + _Close_0 = Marshal.GetFunctionPointerForDelegate(closeDelegate = Do_Abi_Close_0).ToPointer() -#else - _Close_0 = (delegate*)&Do_Abi_Close_0 -#endif + }; var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 1); Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_Close_0(IntPtr thisPtr) { diff --git a/WinRT.Runtime/Projections/IEnumerable.net5.cs b/WinRT.Runtime/Projections/IEnumerable.net5.cs new file mode 100644 index 000000000..8dd61983e --- /dev/null +++ b/WinRT.Runtime/Projections/IEnumerable.net5.cs @@ -0,0 +1,638 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; +using System.Diagnostics; +using Microsoft.UI.Xaml.Interop; + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Windows.Foundation.Collections +{ + [Guid("FAA585EA-6214-4217-AFDA-7F46DE5869B3")] + internal interface IIterable + { + IIterator First(); + } + [Guid("6A79E863-4300-459A-9966-CBB660963EE1")] + internal interface IIterator + { + bool _MoveNext(); + uint GetMany(ref T[] items); + T _Current { get; } + bool HasCurrent { get; } + } +} + +namespace ABI.Windows.Foundation.Collections +{ + [DynamicInterfaceCastableImplementation] + [Guid("FAA585EA-6214-4217-AFDA-7F46DE5869B3")] + internal interface IIterable : ABI.System.Collections.Generic.IEnumerable + { + public static Guid PIID = ABI.System.Collections.Generic.IEnumerable.PIID; + } +} + +namespace ABI.System.Collections.Generic +{ + using global::System; + using global::System.Runtime.CompilerServices; + + [DynamicInterfaceCastableImplementation] + [Guid("FAA585EA-6214-4217-AFDA-7F46DE5869B3")] + interface 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))); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static IntPtr FromManaged(global::System.Collections.Generic.IEnumerable value) => + (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); + + public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IEnumerable)); + + public class FromAbiHelper : global::System.Collections.Generic.IEnumerable + { + private readonly global::System.Collections.Generic.IEnumerable _iterable; + + public FromAbiHelper(global::System.Collections.Generic.IEnumerable iterable) + { + _iterable = iterable; + } + + public global::System.Collections.Generic.IEnumerator GetEnumerator() + { + var first = ((global::Windows.Foundation.Collections.IIterable)(IWinRTObject)_iterable).First(); + if (first is global::ABI.System.Collections.Generic.IEnumerator iterator) + { + return iterator; + } + throw new InvalidOperationException("Unexpected type for enumerator"); + } + + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + + internal sealed class ToAbiHelper : global::Windows.Foundation.Collections.IIterable + { + private readonly IEnumerable m_enumerable; + + internal ToAbiHelper(IEnumerable enumerable) => m_enumerable = enumerable; + + public global::Windows.Foundation.Collections.IIterator First() => + new IEnumerator.ToAbiHelper(m_enumerable.GetEnumerator()); + } + + [Guid("FAA585EA-6214-4217-AFDA-7F46DE5869B3")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public IEnumerable_Delegates.First_0 First_0; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IEnumerable)); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + First_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6]); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + First_0 = Do_Abi_First_0 + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 1); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.First_0); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static unsafe int Do_Abi_First_0(IntPtr thisPtr, out IntPtr __return_value__) + { + __return_value__ = default; + try + { + var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); + __return_value__ = MarshalInterface>.FromManaged(__this.GetEnumerator()); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + + public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + public static Guid PIID = Vftbl.PIID; + + private static FromAbiHelper _FromIterable(IWinRTObject _this) + { + return (FromAbiHelper)_this.GetOrCreateTypeHelperData(typeof(global::System.Collections.Generic.IEnumerable).TypeHandle, + () => new FromAbiHelper((global::System.Collections.Generic.IEnumerable)_this)); + } + + unsafe global::Windows.Foundation.Collections.IIterator global::Windows.Foundation.Collections.IIterable.First() + { + IntPtr __retval = default; + try + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IEnumerable).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.First_0(ThisPtr, out __retval)); + return ABI.System.Collections.Generic.IEnumerator.FromAbiInternal(__retval); + } + finally + { + ABI.System.Collections.Generic.IEnumerator.DisposeAbi(__retval); + } + } + + 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 + { + 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 + { + public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IEnumerator obj) => + obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IEnumerator))); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static global::System.Collections.Generic.IEnumerator FromAbi(IntPtr thisPtr) => + thisPtr == IntPtr.Zero ? null : new IEnumerator(ObjRefFromAbi(thisPtr)); + + internal static global::Windows.Foundation.Collections.IIterator FromAbiInternal(IntPtr thisPtr) => + new IEnumerator(ObjRefFromAbi(thisPtr)); + + public static IntPtr FromManaged(global::System.Collections.Generic.IEnumerator value) => + (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); + + public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IEnumerator)); + + public class FromAbiHelper : global::System.Collections.Generic.IEnumerator + { + private readonly global::Windows.Foundation.Collections.IIterator _iterator; + + public FromAbiHelper(IObjectReference obj) : + this(new global::ABI.System.Collections.Generic.IEnumerator(obj)) + { + } + + internal FromAbiHelper(global::Windows.Foundation.Collections.IIterator iterator) + { + _iterator = iterator; + } + + private bool m_hadCurrent = true; + private T m_current = default!; + private bool m_isInitialized = false; + + public T Current + { + get + { + // The enumerator has not been advanced to the first element yet. + if (!m_isInitialized) + throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumNotStarted); + // The enumerator has reached the end of the collection + if (!m_hadCurrent) + throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumEnded); + return m_current; + } + } + + object IEnumerator.Current + { + get + { + // The enumerator has not been advanced to the first element yet. + if (!m_isInitialized) + throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumNotStarted); + // The enumerator has reached the end of the collection + if (!m_hadCurrent) + throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumEnded); + return m_current; + } + } + + public bool MoveNext() + { + // If we've passed the end of the iteration, IEnumerable should return false, while + // IIterable will fail the interface call + if (!m_hadCurrent) + { + return false; + } + + // IIterators start at index 0, rather than -1. If this is the first call, we need to just + // check HasCurrent rather than actually moving to the next element + try + { + if (!m_isInitialized) + { + m_hadCurrent = _iterator.HasCurrent; + m_isInitialized = true; + } + else + { + m_hadCurrent = _iterator._MoveNext(); + } + + // We want to save away the current value for two reasons: + // 1. Accessing .Current is cheap on other iterators, so having it be a property which is a + // simple field access preserves the expected performance characteristics (as opposed to + // triggering a COM call every time the property is accessed) + // + // 2. This allows us to preserve the same semantics as generic collection iteration when iterating + // beyond the end of the collection - namely that Current continues to return the last value + // of the collection + if (m_hadCurrent) + { + m_current = _iterator._Current; + } + } + catch (Exception e) + { + // Translate E_CHANGED_STATE into an InvalidOperationException for an updated enumeration + if (Marshal.GetHRForException(e) == ExceptionHelpers.E_CHANGED_STATE) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumFailedVersion); + } + else + { + throw; + } + } + + return m_hadCurrent; + } + + public void Reset() + { + throw new NotSupportedException(); + } + + public void Dispose() + { + } + } + + public sealed class ToAbiHelper : global::Windows.Foundation.Collections.IIterator, IBindableIterator + { + private readonly global::System.Collections.Generic.IEnumerator m_enumerator; + private bool m_firstItem = true; + private bool m_hasCurrent; + + internal ToAbiHelper(global::System.Collections.Generic.IEnumerator enumerator) => m_enumerator = enumerator; + + public T _Current + { + get + { + // IEnumerator starts at item -1, while IIterators start at item 0. Therefore, if this is the + // first access to the iterator we need to advance to the first item. + if (m_firstItem) + { + m_firstItem = false; + _MoveNext(); + } + + if (!m_hasCurrent) + { + ExceptionHelpers.ThrowExceptionForHR(ExceptionHelpers.E_BOUNDS); + } + + return m_enumerator.Current; + } + } + + public bool HasCurrent + { + get + { + // IEnumerator starts at item -1, while IIterators start at item 0. Therefore, if this is the + // first access to the iterator we need to advance to the first item. + if (m_firstItem) + { + m_firstItem = false; + _MoveNext(); + } + + return m_hasCurrent; + } + } + + public bool _MoveNext() + { + try + { + m_hasCurrent = m_enumerator.MoveNext(); + } + catch (InvalidOperationException) + { + ExceptionHelpers.ThrowExceptionForHR(ExceptionHelpers.E_CHANGED_STATE); + } + + return m_hasCurrent; + } + + public uint GetMany(ref T[] items) + { + if (items == null) + { + return 0; + } + + int index = 0; + while (index < items.Length && HasCurrent) + { + items[index] = _Current; + _MoveNext(); + ++index; + } + + if (typeof(T) == typeof(string)) + { + string[] stringItems = (items as string[])!; + + // Fill the rest of the array with string.Empty to avoid marshaling failure + for (int i = index; i < items.Length; ++i) + stringItems[i] = string.Empty; + } + + return (uint)index; + } + + public object Current => _Current; + + public bool MoveNext() => _MoveNext(); + } + + [Guid("6A79E863-4300-459A-9966-CBB660963EE1")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate get_Current_0; + internal _get_PropertyAsBoolean get_HasCurrent_1; + public IEnumerator_Delegates.MoveNext_2 MoveNext_2; + public IEnumerator_Delegates.GetMany_3 GetMany_3; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IEnumerator)); + private static readonly Type get_Current_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType.MakeByRefType(), typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + get_Current_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], get_Current_0_Type); + get_HasCurrent_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsBoolean>(vftbl[7]); + MoveNext_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8]); + GetMany_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9]); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + get_Current_0 = global::System.Delegate.CreateDelegate(get_Current_0_Type, typeof(Vftbl).GetMethod("Do_Abi_get_Current_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + get_HasCurrent_1 = Do_Abi_get_HasCurrent_1, + MoveNext_2 = Do_Abi_MoveNext_2, + GetMany_3 = Do_Abi_GetMany_3 + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 4); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Current_0); + nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_HasCurrent_1); + nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.MoveNext_2); + nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetMany_3); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable, ToAbiHelper> _adapterTable = + new ConditionalWeakTable, ToAbiHelper>(); + + private static ToAbiHelper FindAdapter(IntPtr thisPtr) + { + var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); + return _adapterTable.GetValue(__this, (enumerator) => new ToAbiHelper(enumerator)); + } + + private static unsafe int Do_Abi_MoveNext_2(IntPtr thisPtr, out byte __return_value__) + { + bool ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr)._MoveNext(); + __return_value__ = (byte)(____return_value__ ? 1 : 0); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_GetMany_3(IntPtr thisPtr, int __itemsSize, IntPtr items, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + T[] __items = Marshaler.FromAbiArray((__itemsSize, items)); + + try + { + ____return_value__ = FindAdapter(thisPtr).GetMany(ref __items); + Marshaler.CopyManagedArray(__items, items); + __return_value__ = ____return_value__; + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_get_Current_0(void* thisPtr, out TAbi __return_value__) + { + T ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr))._Current; + __return_value__ = (TAbi)Marshaler.FromManaged(____return_value__); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + private static unsafe int Do_Abi_get_HasCurrent_1(IntPtr thisPtr, out byte __return_value__) + { + bool ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).HasCurrent; + __return_value__ = (byte)(____return_value__ ? 1 : 0); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + public static Guid PIID = Vftbl.PIID; + + public static implicit operator IEnumerator(IObjectReference obj) => (obj != null) ? new IEnumerator(obj) : null; + public static implicit operator IEnumerator(ObjectReference obj) => (obj != null) ? new IEnumerator(obj) : null; + protected readonly ObjectReference _obj; + public IObjectReference ObjRef { get => _obj; } + + public IntPtr ThisPtr => _obj.ThisPtr; + + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + + public IEnumerator(IObjectReference obj) : this(obj.As()) { } + public IEnumerator(ObjectReference obj) + { + _obj = obj; + _FromIterator = new FromAbiHelper(this); + } + FromAbiHelper _FromIterator; + + public unsafe bool _MoveNext() + { + byte __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.MoveNext_2(ThisPtr, out __retval)); + return __retval != 0; + } + + public unsafe uint GetMany(ref T[] items) + { + object __items = default; + int __items_length = default; + IntPtr __items_data = default; + uint __retval = default; + try + { + __items = Marshaler.CreateMarshalerArray(items); + (__items_length, __items_data) = Marshaler.GetAbiArray(__items); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetMany_3(ThisPtr, __items_length, __items_data, out __retval)); + items = Marshaler.FromAbiArray((__items_length, __items_data)); + return __retval; + } + finally + { + Marshaler.DisposeMarshalerArray(__items); + } + } + + public unsafe T _Current + { + get + { + var __params = new object[] { ThisPtr, null }; + try + { + _obj.Vftbl.get_Current_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[1]); + } + finally + { + Marshaler.DisposeAbi(__params[1]); + } + } + } + + public unsafe bool HasCurrent + { + get + { + byte __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_HasCurrent_1(ThisPtr, out __retval)); + return __retval != 0; + } + } + + public bool MoveNext() => _FromIterator.MoveNext(); + public void Reset() => _FromIterator.Reset(); + public void Dispose() => _FromIterator.Dispose(); + public T Current => _FromIterator.Current; + object IEnumerator.Current => Current; + } + public 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/WinRT.Runtime/Projections/IEnumerable.cs b/WinRT.Runtime/Projections/IEnumerable.netstandard2.0.cs similarity index 97% rename from WinRT.Runtime/Projections/IEnumerable.cs rename to WinRT.Runtime/Projections/IEnumerable.netstandard2.0.cs index 137b5f6cb..b0e1ab4aa 100644 --- a/WinRT.Runtime/Projections/IEnumerable.cs +++ b/WinRT.Runtime/Projections/IEnumerable.netstandard2.0.cs @@ -1,643 +1,643 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.InteropServices; -using WinRT; -using WinRT.Interop; -using System.Diagnostics; -using Microsoft.UI.Xaml.Interop; - -#pragma warning disable 0169 // warning CS0169: The field '...' is never used -#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to - -namespace Windows.Foundation.Collections -{ - [Guid("FAA585EA-6214-4217-AFDA-7F46DE5869B3")] - internal interface IIterable - { - IIterator First(); - } - [Guid("6A79E863-4300-459A-9966-CBB660963EE1")] - internal interface IIterator - { - bool _MoveNext(); - uint GetMany(ref T[] items); - T _Current { get; } - bool HasCurrent { get; } - } -} - -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 - { - public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IEnumerable obj) => - obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IEnumerable))); - - public static IntPtr GetAbi(IObjectReference objRef) => - objRef?.ThisPtr ?? IntPtr.Zero; - - public static global::System.Collections.Generic.IEnumerable FromAbi(IntPtr thisPtr) => - thisPtr == IntPtr.Zero ? null : new IEnumerable(ObjRefFromAbi(thisPtr)); - - public static IntPtr FromManaged(global::System.Collections.Generic.IEnumerable value) => - (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); - - public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); - - public static void DisposeAbi(IntPtr abi) => - MarshalInterfaceHelper>.DisposeAbi(abi); - - public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IEnumerable)); - - public class FromAbiHelper : global::System.Collections.Generic.IEnumerable - { - private readonly global::ABI.System.Collections.Generic.IEnumerable _iterable; - - public FromAbiHelper(IObjectReference obj) : - this(new global::ABI.System.Collections.Generic.IEnumerable(obj)) - { - } - - public FromAbiHelper(global::ABI.System.Collections.Generic.IEnumerable iterable) - { - _iterable = iterable; - } - - public global::System.Collections.Generic.IEnumerator GetEnumerator() - { - var first = ((global::Windows.Foundation.Collections.IIterable)_iterable).First(); - if (first is global::ABI.System.Collections.Generic.IEnumerator iterator) - { - return iterator; - } - throw new InvalidOperationException("Unexpected type for enumerator"); - } - - global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - } - - internal sealed class ToAbiHelper : global::Windows.Foundation.Collections.IIterable - { - private readonly IEnumerable m_enumerable; - - internal ToAbiHelper(IEnumerable enumerable) => m_enumerable = enumerable; - - public global::Windows.Foundation.Collections.IIterator First() => - new IEnumerator.ToAbiHelper(m_enumerable.GetEnumerator()); - } - - [Guid("FAA585EA-6214-4217-AFDA-7F46DE5869B3")] - public struct Vftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - public IEnumerable_Delegates.First_0 First_0; - public static Guid PIID = GuidGenerator.CreateIID(typeof(IEnumerable)); - - internal unsafe Vftbl(IntPtr thisPtr) - { - var vftblPtr = Marshal.PtrToStructure(thisPtr); - var vftbl = (IntPtr*)vftblPtr.Vftbl; - IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); - First_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6]); - } - - private static readonly Vftbl AbiToProjectionVftable; - public static readonly IntPtr AbiToProjectionVftablePtr; - static unsafe Vftbl() - { - AbiToProjectionVftable = new Vftbl - { - IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, - First_0 = Do_Abi_First_0 - }; - var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 1); - Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); - nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.First_0); - - AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; - } - - private static unsafe int Do_Abi_First_0(IntPtr thisPtr, out IntPtr __return_value__) - { - __return_value__ = default; - try - { - var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); - __return_value__ = MarshalInterface>.FromManaged(__this.GetEnumerator()); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - } - - public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) - { - if (thisPtr == IntPtr.Zero) - { - return null; - } - var vftblT = new Vftbl(thisPtr); - return ObjectReference.FromAbi(thisPtr, vftblT); - } - public static Guid PIID = Vftbl.PIID; - - public static implicit operator IEnumerable(IObjectReference obj) => (obj != null) ? new IEnumerable(obj) : null; - public static implicit operator IEnumerable(ObjectReference obj) => (obj != null) ? new IEnumerable(obj) : null; - protected readonly ObjectReference _obj; - public IObjectReference ObjRef { get => _obj; } - - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - public IEnumerable(IObjectReference obj) : this(obj.As()) { } - public IEnumerable(ObjectReference obj) - { - _obj = obj; - _FromIterable = new FromAbiHelper(this); - } - FromAbiHelper _FromIterable; - - unsafe global::Windows.Foundation.Collections.IIterator global::Windows.Foundation.Collections.IIterable.First() - { - IntPtr __retval = default; - try - { - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.First_0(ThisPtr, out __retval)); - return ABI.System.Collections.Generic.IEnumerator.FromAbiInternal(__retval); - } - finally - { - ABI.System.Collections.Generic.IEnumerator.DisposeAbi(__retval); - } - } - - public global::System.Collections.Generic.IEnumerator GetEnumerator() => _FromIterable.GetEnumerator(); - IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - } - 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 - { - public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IEnumerator obj) => - obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IEnumerator))); - - public static IntPtr GetAbi(IObjectReference objRef) => - objRef?.ThisPtr ?? IntPtr.Zero; - - public static global::System.Collections.Generic.IEnumerator FromAbi(IntPtr thisPtr) => - thisPtr == IntPtr.Zero ? null : new IEnumerator(ObjRefFromAbi(thisPtr)); - - internal static global::Windows.Foundation.Collections.IIterator FromAbiInternal(IntPtr thisPtr) => - new IEnumerator(ObjRefFromAbi(thisPtr)); - - public static IntPtr FromManaged(global::System.Collections.Generic.IEnumerator value) => - (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); - - public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); - - public static void DisposeAbi(IntPtr abi) => - MarshalInterfaceHelper>.DisposeAbi(abi); - - public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IEnumerator)); - - public class FromAbiHelper : global::System.Collections.Generic.IEnumerator - { - private readonly global::Windows.Foundation.Collections.IIterator _iterator; - - public FromAbiHelper(IObjectReference obj) : - this(new global::ABI.System.Collections.Generic.IEnumerator(obj)) - { - } - - internal FromAbiHelper(global::Windows.Foundation.Collections.IIterator iterator) - { - _iterator = iterator; - } - - private bool m_hadCurrent = true; - private T m_current = default!; - private bool m_isInitialized = false; - - public T Current - { - get - { - // The enumerator has not been advanced to the first element yet. - if (!m_isInitialized) - throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumNotStarted); - // The enumerator has reached the end of the collection - if (!m_hadCurrent) - throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumEnded); - return m_current; - } - } - - object IEnumerator.Current - { - get - { - // The enumerator has not been advanced to the first element yet. - if (!m_isInitialized) - throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumNotStarted); - // The enumerator has reached the end of the collection - if (!m_hadCurrent) - throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumEnded); - return m_current; - } - } - - public bool MoveNext() - { - // If we've passed the end of the iteration, IEnumerable should return false, while - // IIterable will fail the interface call - if (!m_hadCurrent) - { - return false; - } - - // IIterators start at index 0, rather than -1. If this is the first call, we need to just - // check HasCurrent rather than actually moving to the next element - try - { - if (!m_isInitialized) - { - m_hadCurrent = _iterator.HasCurrent; - m_isInitialized = true; - } - else - { - m_hadCurrent = _iterator._MoveNext(); - } - - // We want to save away the current value for two reasons: - // 1. Accessing .Current is cheap on other iterators, so having it be a property which is a - // simple field access preserves the expected performance characteristics (as opposed to - // triggering a COM call every time the property is accessed) - // - // 2. This allows us to preserve the same semantics as generic collection iteration when iterating - // beyond the end of the collection - namely that Current continues to return the last value - // of the collection - if (m_hadCurrent) - { - m_current = _iterator._Current; - } - } - catch (Exception e) - { - // Translate E_CHANGED_STATE into an InvalidOperationException for an updated enumeration - if (Marshal.GetHRForException(e) == ExceptionHelpers.E_CHANGED_STATE) - { - throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumFailedVersion); - } - else - { - throw; - } - } - - return m_hadCurrent; - } - - public void Reset() - { - throw new NotSupportedException(); - } - - public void Dispose() - { - } - } - - public sealed class ToAbiHelper : global::Windows.Foundation.Collections.IIterator, IBindableIterator - { - private readonly global::System.Collections.Generic.IEnumerator m_enumerator; - private bool m_firstItem = true; - private bool m_hasCurrent; - - internal ToAbiHelper(global::System.Collections.Generic.IEnumerator enumerator) => m_enumerator = enumerator; - - public T _Current - { - get - { - // IEnumerator starts at item -1, while IIterators start at item 0. Therefore, if this is the - // first access to the iterator we need to advance to the first item. - if (m_firstItem) - { - m_firstItem = false; - _MoveNext(); - } - - if (!m_hasCurrent) - { - ExceptionHelpers.ThrowExceptionForHR(ExceptionHelpers.E_BOUNDS); - } - - return m_enumerator.Current; - } - } - - public bool HasCurrent - { - get - { - // IEnumerator starts at item -1, while IIterators start at item 0. Therefore, if this is the - // first access to the iterator we need to advance to the first item. - if (m_firstItem) - { - m_firstItem = false; - _MoveNext(); - } - - return m_hasCurrent; - } - } - - public bool _MoveNext() - { - try - { - m_hasCurrent = m_enumerator.MoveNext(); - } - catch (InvalidOperationException) - { - ExceptionHelpers.ThrowExceptionForHR(ExceptionHelpers.E_CHANGED_STATE); - } - - return m_hasCurrent; - } - - public uint GetMany(ref T[] items) - { - if (items == null) - { - return 0; - } - - int index = 0; - while (index < items.Length && HasCurrent) - { - items[index] = _Current; - _MoveNext(); - ++index; - } - - if (typeof(T) == typeof(string)) - { - string[] stringItems = (items as string[])!; - - // Fill the rest of the array with string.Empty to avoid marshaling failure - for (int i = index; i < items.Length; ++i) - stringItems[i] = string.Empty; - } - - return (uint)index; - } - - public object Current => _Current; - - public bool MoveNext() => _MoveNext(); - } - - [Guid("6A79E863-4300-459A-9966-CBB660963EE1")] - public struct Vftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - public global::System.Delegate get_Current_0; - internal _get_PropertyAsBoolean get_HasCurrent_1; - public IEnumerator_Delegates.MoveNext_2 MoveNext_2; - public IEnumerator_Delegates.GetMany_3 GetMany_3; - public static Guid PIID = GuidGenerator.CreateIID(typeof(IEnumerator)); - private static readonly Type get_Current_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType.MakeByRefType(), typeof(int) }); - - internal unsafe Vftbl(IntPtr thisPtr) - { - var vftblPtr = Marshal.PtrToStructure(thisPtr); - var vftbl = (IntPtr*)vftblPtr.Vftbl; - IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); - get_Current_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], get_Current_0_Type); - get_HasCurrent_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsBoolean>(vftbl[7]); - MoveNext_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8]); - GetMany_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9]); - } - - private static readonly Vftbl AbiToProjectionVftable; - public static readonly IntPtr AbiToProjectionVftablePtr; - static unsafe Vftbl() - { - AbiToProjectionVftable = new Vftbl - { - IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, - get_Current_0 = global::System.Delegate.CreateDelegate(get_Current_0_Type, typeof(Vftbl).GetMethod("Do_Abi_get_Current_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), - get_HasCurrent_1 = Do_Abi_get_HasCurrent_1, - MoveNext_2 = Do_Abi_MoveNext_2, - GetMany_3 = Do_Abi_GetMany_3 - }; - var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 4); - Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); - nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Current_0); - nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_HasCurrent_1); - nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.MoveNext_2); - nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetMany_3); - - AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; - } - - private static ConditionalWeakTable, ToAbiHelper> _adapterTable = - new ConditionalWeakTable, ToAbiHelper>(); - - private static ToAbiHelper FindAdapter(IntPtr thisPtr) - { - var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); - return _adapterTable.GetValue(__this, (enumerator) => new ToAbiHelper(enumerator)); - } - - private static unsafe int Do_Abi_MoveNext_2(IntPtr thisPtr, out byte __return_value__) - { - bool ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(thisPtr)._MoveNext(); - __return_value__ = (byte)(____return_value__ ? 1 : 0); - - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_GetMany_3(IntPtr thisPtr, int __itemsSize, IntPtr items, out uint __return_value__) - { - uint ____return_value__ = default; - - __return_value__ = default; - T[] __items = Marshaler.FromAbiArray((__itemsSize, items)); - - try - { - ____return_value__ = FindAdapter(thisPtr).GetMany(ref __items); - Marshaler.CopyManagedArray(__items, items); - __return_value__ = ____return_value__; - - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_get_Current_0(void* thisPtr, out TAbi __return_value__) - { - T ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(new IntPtr(thisPtr))._Current; - __return_value__ = (TAbi)Marshaler.FromManaged(____return_value__); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - - private static unsafe int Do_Abi_get_HasCurrent_1(IntPtr thisPtr, out byte __return_value__) - { - bool ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(thisPtr).HasCurrent; - __return_value__ = (byte)(____return_value__ ? 1 : 0); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - } - public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) - { - if (thisPtr == IntPtr.Zero) - { - return null; - } - var vftblT = new Vftbl(thisPtr); - return ObjectReference.FromAbi(thisPtr, vftblT); - } - public static Guid PIID = Vftbl.PIID; - - public static implicit operator IEnumerator(IObjectReference obj) => (obj != null) ? new IEnumerator(obj) : null; - public static implicit operator IEnumerator(ObjectReference obj) => (obj != null) ? new IEnumerator(obj) : null; - protected readonly ObjectReference _obj; - public IObjectReference ObjRef { get => _obj; } - - public IntPtr ThisPtr => _obj.ThisPtr; - - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - - public IEnumerator(IObjectReference obj) : this(obj.As()) { } - public IEnumerator(ObjectReference obj) - { - _obj = obj; - _FromIterator = new FromAbiHelper(this); - } - FromAbiHelper _FromIterator; - - public unsafe bool _MoveNext() - { - byte __retval = default; - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.MoveNext_2(ThisPtr, out __retval)); - return __retval != 0; - } - - public unsafe uint GetMany(ref T[] items) - { - object __items = default; - int __items_length = default; - IntPtr __items_data = default; - uint __retval = default; - try - { - __items = Marshaler.CreateMarshalerArray(items); - (__items_length, __items_data) = Marshaler.GetAbiArray(__items); - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetMany_3(ThisPtr, __items_length, __items_data, out __retval)); - items = Marshaler.FromAbiArray((__items_length, __items_data)); - return __retval; - } - finally - { - Marshaler.DisposeMarshalerArray(__items); - } - } - - public unsafe T _Current - { - get - { - var __params = new object[] { ThisPtr, null }; - try - { - _obj.Vftbl.get_Current_0.DynamicInvokeAbi(__params); - return Marshaler.FromAbi(__params[1]); - } - finally - { - Marshaler.DisposeAbi(__params[1]); - } - } - } - - public unsafe bool HasCurrent - { - get - { - byte __retval = default; - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_HasCurrent_1(ThisPtr, out __retval)); - return __retval != 0; - } - } - - public bool MoveNext() => _FromIterator.MoveNext(); - public void Reset() => _FromIterator.Reset(); - public void Dispose() => _FromIterator.Dispose(); - public T Current => _FromIterator.Current; - object IEnumerator.Current => Current; - } - public 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__); - } -} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; +using System.Diagnostics; +using Microsoft.UI.Xaml.Interop; + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Windows.Foundation.Collections +{ + [Guid("FAA585EA-6214-4217-AFDA-7F46DE5869B3")] + internal interface IIterable + { + IIterator First(); + } + [Guid("6A79E863-4300-459A-9966-CBB660963EE1")] + internal interface IIterator + { + bool _MoveNext(); + uint GetMany(ref T[] items); + T _Current { get; } + bool HasCurrent { get; } + } +} + +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 + { + public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IEnumerable obj) => + obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IEnumerable))); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static global::System.Collections.Generic.IEnumerable FromAbi(IntPtr thisPtr) => + thisPtr == IntPtr.Zero ? null : new IEnumerable(ObjRefFromAbi(thisPtr)); + + public static IntPtr FromManaged(global::System.Collections.Generic.IEnumerable value) => + (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); + + public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IEnumerable)); + + public class FromAbiHelper : global::System.Collections.Generic.IEnumerable + { + private readonly global::ABI.System.Collections.Generic.IEnumerable _iterable; + + public FromAbiHelper(IObjectReference obj) : + this(new global::ABI.System.Collections.Generic.IEnumerable(obj)) + { + } + + public FromAbiHelper(global::ABI.System.Collections.Generic.IEnumerable iterable) + { + _iterable = iterable; + } + + public global::System.Collections.Generic.IEnumerator GetEnumerator() + { + var first = ((global::Windows.Foundation.Collections.IIterable)_iterable).First(); + if (first is global::ABI.System.Collections.Generic.IEnumerator iterator) + { + return iterator; + } + throw new InvalidOperationException("Unexpected type for enumerator"); + } + + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + + internal sealed class ToAbiHelper : global::Windows.Foundation.Collections.IIterable + { + private readonly IEnumerable m_enumerable; + + internal ToAbiHelper(IEnumerable enumerable) => m_enumerable = enumerable; + + public global::Windows.Foundation.Collections.IIterator First() => + new IEnumerator.ToAbiHelper(m_enumerable.GetEnumerator()); + } + + [Guid("FAA585EA-6214-4217-AFDA-7F46DE5869B3")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public IEnumerable_Delegates.First_0 First_0; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IEnumerable)); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + First_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6]); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + First_0 = Do_Abi_First_0 + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 1); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.First_0); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static unsafe int Do_Abi_First_0(IntPtr thisPtr, out IntPtr __return_value__) + { + __return_value__ = default; + try + { + var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); + __return_value__ = MarshalInterface>.FromManaged(__this.GetEnumerator()); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + + public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + public static Guid PIID = Vftbl.PIID; + + public static implicit operator IEnumerable(IObjectReference obj) => (obj != null) ? new IEnumerable(obj) : null; + public static implicit operator IEnumerable(ObjectReference obj) => (obj != null) ? new IEnumerable(obj) : null; + protected readonly ObjectReference _obj; + public IObjectReference ObjRef { get => _obj; } + + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public IEnumerable(IObjectReference obj) : this(obj.As()) { } + public IEnumerable(ObjectReference obj) + { + _obj = obj; + _FromIterable = new FromAbiHelper(this); + } + FromAbiHelper _FromIterable; + + unsafe global::Windows.Foundation.Collections.IIterator global::Windows.Foundation.Collections.IIterable.First() + { + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.First_0(ThisPtr, out __retval)); + return ABI.System.Collections.Generic.IEnumerator.FromAbiInternal(__retval); + } + finally + { + ABI.System.Collections.Generic.IEnumerator.DisposeAbi(__retval); + } + } + + public global::System.Collections.Generic.IEnumerator GetEnumerator() => _FromIterable.GetEnumerator(); + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + 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 + { + public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IEnumerator obj) => + obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IEnumerator))); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static global::System.Collections.Generic.IEnumerator FromAbi(IntPtr thisPtr) => + thisPtr == IntPtr.Zero ? null : new IEnumerator(ObjRefFromAbi(thisPtr)); + + internal static global::Windows.Foundation.Collections.IIterator FromAbiInternal(IntPtr thisPtr) => + new IEnumerator(ObjRefFromAbi(thisPtr)); + + public static IntPtr FromManaged(global::System.Collections.Generic.IEnumerator value) => + (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); + + public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IEnumerator)); + + public class FromAbiHelper : global::System.Collections.Generic.IEnumerator + { + private readonly global::Windows.Foundation.Collections.IIterator _iterator; + + public FromAbiHelper(IObjectReference obj) : + this(new global::ABI.System.Collections.Generic.IEnumerator(obj)) + { + } + + internal FromAbiHelper(global::Windows.Foundation.Collections.IIterator iterator) + { + _iterator = iterator; + } + + private bool m_hadCurrent = true; + private T m_current = default!; + private bool m_isInitialized = false; + + public T Current + { + get + { + // The enumerator has not been advanced to the first element yet. + if (!m_isInitialized) + throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumNotStarted); + // The enumerator has reached the end of the collection + if (!m_hadCurrent) + throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumEnded); + return m_current; + } + } + + object IEnumerator.Current + { + get + { + // The enumerator has not been advanced to the first element yet. + if (!m_isInitialized) + throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumNotStarted); + // The enumerator has reached the end of the collection + if (!m_hadCurrent) + throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumEnded); + return m_current; + } + } + + public bool MoveNext() + { + // If we've passed the end of the iteration, IEnumerable should return false, while + // IIterable will fail the interface call + if (!m_hadCurrent) + { + return false; + } + + // IIterators start at index 0, rather than -1. If this is the first call, we need to just + // check HasCurrent rather than actually moving to the next element + try + { + if (!m_isInitialized) + { + m_hadCurrent = _iterator.HasCurrent; + m_isInitialized = true; + } + else + { + m_hadCurrent = _iterator._MoveNext(); + } + + // We want to save away the current value for two reasons: + // 1. Accessing .Current is cheap on other iterators, so having it be a property which is a + // simple field access preserves the expected performance characteristics (as opposed to + // triggering a COM call every time the property is accessed) + // + // 2. This allows us to preserve the same semantics as generic collection iteration when iterating + // beyond the end of the collection - namely that Current continues to return the last value + // of the collection + if (m_hadCurrent) + { + m_current = _iterator._Current; + } + } + catch (Exception e) + { + // Translate E_CHANGED_STATE into an InvalidOperationException for an updated enumeration + if (Marshal.GetHRForException(e) == ExceptionHelpers.E_CHANGED_STATE) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumFailedVersion); + } + else + { + throw; + } + } + + return m_hadCurrent; + } + + public void Reset() + { + throw new NotSupportedException(); + } + + public void Dispose() + { + } + } + + public sealed class ToAbiHelper : global::Windows.Foundation.Collections.IIterator, IBindableIterator + { + private readonly global::System.Collections.Generic.IEnumerator m_enumerator; + private bool m_firstItem = true; + private bool m_hasCurrent; + + internal ToAbiHelper(global::System.Collections.Generic.IEnumerator enumerator) => m_enumerator = enumerator; + + public T _Current + { + get + { + // IEnumerator starts at item -1, while IIterators start at item 0. Therefore, if this is the + // first access to the iterator we need to advance to the first item. + if (m_firstItem) + { + m_firstItem = false; + _MoveNext(); + } + + if (!m_hasCurrent) + { + ExceptionHelpers.ThrowExceptionForHR(ExceptionHelpers.E_BOUNDS); + } + + return m_enumerator.Current; + } + } + + public bool HasCurrent + { + get + { + // IEnumerator starts at item -1, while IIterators start at item 0. Therefore, if this is the + // first access to the iterator we need to advance to the first item. + if (m_firstItem) + { + m_firstItem = false; + _MoveNext(); + } + + return m_hasCurrent; + } + } + + public bool _MoveNext() + { + try + { + m_hasCurrent = m_enumerator.MoveNext(); + } + catch (InvalidOperationException) + { + ExceptionHelpers.ThrowExceptionForHR(ExceptionHelpers.E_CHANGED_STATE); + } + + return m_hasCurrent; + } + + public uint GetMany(ref T[] items) + { + if (items == null) + { + return 0; + } + + int index = 0; + while (index < items.Length && HasCurrent) + { + items[index] = _Current; + _MoveNext(); + ++index; + } + + if (typeof(T) == typeof(string)) + { + string[] stringItems = (items as string[])!; + + // Fill the rest of the array with string.Empty to avoid marshaling failure + for (int i = index; i < items.Length; ++i) + stringItems[i] = string.Empty; + } + + return (uint)index; + } + + public object Current => _Current; + + public bool MoveNext() => _MoveNext(); + } + + [Guid("6A79E863-4300-459A-9966-CBB660963EE1")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate get_Current_0; + internal _get_PropertyAsBoolean get_HasCurrent_1; + public IEnumerator_Delegates.MoveNext_2 MoveNext_2; + public IEnumerator_Delegates.GetMany_3 GetMany_3; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IEnumerator)); + private static readonly Type get_Current_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType.MakeByRefType(), typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + get_Current_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], get_Current_0_Type); + get_HasCurrent_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsBoolean>(vftbl[7]); + MoveNext_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8]); + GetMany_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9]); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + get_Current_0 = global::System.Delegate.CreateDelegate(get_Current_0_Type, typeof(Vftbl).GetMethod("Do_Abi_get_Current_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + get_HasCurrent_1 = Do_Abi_get_HasCurrent_1, + MoveNext_2 = Do_Abi_MoveNext_2, + GetMany_3 = Do_Abi_GetMany_3 + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 4); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Current_0); + nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_HasCurrent_1); + nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.MoveNext_2); + nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetMany_3); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable, ToAbiHelper> _adapterTable = + new ConditionalWeakTable, ToAbiHelper>(); + + private static ToAbiHelper FindAdapter(IntPtr thisPtr) + { + var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); + return _adapterTable.GetValue(__this, (enumerator) => new ToAbiHelper(enumerator)); + } + + private static unsafe int Do_Abi_MoveNext_2(IntPtr thisPtr, out byte __return_value__) + { + bool ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr)._MoveNext(); + __return_value__ = (byte)(____return_value__ ? 1 : 0); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_GetMany_3(IntPtr thisPtr, int __itemsSize, IntPtr items, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + T[] __items = Marshaler.FromAbiArray((__itemsSize, items)); + + try + { + ____return_value__ = FindAdapter(thisPtr).GetMany(ref __items); + Marshaler.CopyManagedArray(__items, items); + __return_value__ = ____return_value__; + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_get_Current_0(void* thisPtr, out TAbi __return_value__) + { + T ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr))._Current; + __return_value__ = (TAbi)Marshaler.FromManaged(____return_value__); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + private static unsafe int Do_Abi_get_HasCurrent_1(IntPtr thisPtr, out byte __return_value__) + { + bool ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).HasCurrent; + __return_value__ = (byte)(____return_value__ ? 1 : 0); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + public static Guid PIID = Vftbl.PIID; + + public static implicit operator IEnumerator(IObjectReference obj) => (obj != null) ? new IEnumerator(obj) : null; + public static implicit operator IEnumerator(ObjectReference obj) => (obj != null) ? new IEnumerator(obj) : null; + protected readonly ObjectReference _obj; + public IObjectReference ObjRef { get => _obj; } + + public IntPtr ThisPtr => _obj.ThisPtr; + + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + + public IEnumerator(IObjectReference obj) : this(obj.As()) { } + public IEnumerator(ObjectReference obj) + { + _obj = obj; + _FromIterator = new FromAbiHelper(this); + } + FromAbiHelper _FromIterator; + + public unsafe bool _MoveNext() + { + byte __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.MoveNext_2(ThisPtr, out __retval)); + return __retval != 0; + } + + public unsafe uint GetMany(ref T[] items) + { + object __items = default; + int __items_length = default; + IntPtr __items_data = default; + uint __retval = default; + try + { + __items = Marshaler.CreateMarshalerArray(items); + (__items_length, __items_data) = Marshaler.GetAbiArray(__items); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetMany_3(ThisPtr, __items_length, __items_data, out __retval)); + items = Marshaler.FromAbiArray((__items_length, __items_data)); + return __retval; + } + finally + { + Marshaler.DisposeMarshalerArray(__items); + } + } + + public unsafe T _Current + { + get + { + var __params = new object[] { ThisPtr, null }; + try + { + _obj.Vftbl.get_Current_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[1]); + } + finally + { + Marshaler.DisposeAbi(__params[1]); + } + } + } + + public unsafe bool HasCurrent + { + get + { + byte __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_HasCurrent_1(ThisPtr, out __retval)); + return __retval != 0; + } + } + + public bool MoveNext() => _FromIterator.MoveNext(); + public void Reset() => _FromIterator.Reset(); + public void Dispose() => _FromIterator.Dispose(); + public T Current => _FromIterator.Current; + object IEnumerator.Current => Current; + } + public 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/WinRT.Runtime/Projections/IList.net5.cs b/WinRT.Runtime/Projections/IList.net5.cs new file mode 100644 index 000000000..ff2dbbdba --- /dev/null +++ b/WinRT.Runtime/Projections/IList.net5.cs @@ -0,0 +1,938 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; +using System.Diagnostics; + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Windows.Foundation.Collections +{ + [Guid("913337E9-11A1-4345-A3A2-4E7F956E222D")] + interface IVector : IIterable + { + T GetAt(uint index); + IVectorView GetView(); + bool IndexOf(T value, out uint index); + void SetAt(uint index, T value); + void InsertAt(uint index, T value); + void RemoveAt(uint index); + void Append(T value); + void RemoveAtEnd(); + void _Clear(); + uint GetMany(uint startIndex, ref T[] items); + void ReplaceAll(T[] items); + uint Size { get; } + } +} + +namespace ABI.System.Collections.Generic +{ + using global::System; + using global::System.Runtime.CompilerServices; + + [DynamicInterfaceCastableImplementation] + [Guid("913337E9-11A1-4345-A3A2-4E7F956E222D")] + interface IList : global::System.Collections.Generic.IList, global::Windows.Foundation.Collections.IVector + { + public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IList obj) => + obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IList))); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static IntPtr FromManaged(global::System.Collections.Generic.IList value) => + (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); + + public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IList)); + + public class FromAbiHelper : global::System.Collections.Generic.IList + { + private readonly global::Windows.Foundation.Collections.IVector _vector; + + public FromAbiHelper(global::Windows.Foundation.Collections.IVector vector) + { + _vector = vector; + } + + public int Count + { + get + { + uint size = _vector.Size; + if (((uint)int.MaxValue) < size) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); + } + + return (int)size; + } + } + + public bool IsReadOnly { get => false; } + + public void Add(T item) => _vector.Append(item); + + public void Clear() => _vector._Clear(); + + public bool Contains(T item) => _vector.IndexOf(item, out _); + + public void CopyTo(T[] array, int arrayIndex) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + + if (arrayIndex < 0) + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); + + if (array.Length <= arrayIndex && Count > 0) + throw new ArgumentException(ErrorStrings.Argument_IndexOutOfArrayBounds); + + if (array.Length - arrayIndex < Count) + throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); + + + int count = Count; + for (int i = 0; i < count; i++) + { + array[i + arrayIndex] = FromAbiHelper.GetAt(_vector, (uint)i); + } + } + + public bool Remove(T item) + { + uint index; + bool exists = _vector.IndexOf(item, out index); + + if (!exists) + return false; + + if (((uint)int.MaxValue) < index) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); + } + + FromAbiHelper.RemoveAtHelper(_vector, index); + return true; + } + + public T this[int index] { get => Indexer_Get(index); set => Indexer_Set(index, value); } + + private T Indexer_Get(int index) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + return GetAt(_vector, (uint)index); + } + + private void Indexer_Set(int index, T value) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + SetAt(_vector, (uint)index, value); + } + + public int IndexOf(T item) + { + uint index; + bool exists = _vector.IndexOf(item, out index); + + if (!exists) + return -1; + + if (((uint)int.MaxValue) < index) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); + } + + return (int)index; + } + + public void Insert(int index, T item) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + InsertAtHelper(_vector, (uint)index, item); + } + + public void RemoveAt(int index) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + RemoveAtHelper(_vector, (uint)index); + } + + internal static T GetAt(global::Windows.Foundation.Collections.IVector _this, uint index) + { + try + { + return _this.GetAt(index); + + // We delegate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + + throw; + } + } + + private static void SetAt(global::Windows.Foundation.Collections.IVector _this, uint index, T value) + { + try + { + _this.SetAt(index, value); + + // We deligate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + + throw; + } + } + + private static void InsertAtHelper(global::Windows.Foundation.Collections.IVector _this, uint index, T item) + { + try + { + _this.InsertAt(index, item); + + // We delegate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + + throw; + } + } + + internal static void RemoveAtHelper(global::Windows.Foundation.Collections.IVector _this, uint index) + { + try + { + _this.RemoveAt(index); + + // We delegate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + + throw; + } + } + + public global::System.Collections.Generic.IEnumerator GetEnumerator() => ((global::System.Collections.Generic.IEnumerable)(IWinRTObject)_vector).GetEnumerator(); + + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + + public sealed class ToAbiHelper : global::Windows.Foundation.Collections.IVector + { + private global::System.Collections.Generic.IList _list; + + public ToAbiHelper(global::System.Collections.Generic.IList list) => _list = list; + + global::Windows.Foundation.Collections.IIterator global::Windows.Foundation.Collections.IIterable.First() => + new IEnumerator.ToAbiHelper(_list.GetEnumerator()); + + private static void EnsureIndexInt32(uint index, int limit = int.MaxValue) + { + // We use '<=' and not '<' because int.MaxValue == index would imply + // that Size > int.MaxValue: + if (((uint)int.MaxValue) <= index || index >= (uint)limit) + { + Exception e = new ArgumentOutOfRangeException(nameof(index), ErrorStrings.ArgumentOutOfRange_IndexLargerThanMaxValue); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + } + + public T GetAt(uint index) + { + EnsureIndexInt32(index, _list.Count); + + try + { + return _list[(int)index]; + } + catch (ArgumentOutOfRangeException ex) + { + throw ex.GetExceptionForHR(ExceptionHelpers.E_BOUNDS, ErrorStrings.ArgumentOutOfRange_Index); + } + } + + public uint Size => (uint)_list.Count; + + global::Windows.Foundation.Collections.IVectorView global::Windows.Foundation.Collections.IVector.GetView() + { + // Note: This list is not really read-only - you could QI for a modifiable + // list. We gain some perf by doing this. We believe this is acceptable. + if (!(_list is global::System.Collections.Generic.IReadOnlyList roList)) + { + roList = new ReadOnlyCollection(_list); + } + return new IReadOnlyList.ToAbiHelper(roList); + } + + public bool IndexOf(T value, out uint index) + { + int ind = _list.IndexOf(value); + + if (-1 == ind) + { + index = 0; + return false; + } + + index = (uint)ind; + return true; + } + + public void SetAt(uint index, T value) + { + EnsureIndexInt32(index, _list.Count); + + try + { + _list[(int)index] = value; + } + catch (ArgumentOutOfRangeException ex) + { + throw ex.GetExceptionForHR(ExceptionHelpers.E_BOUNDS, ErrorStrings.ArgumentOutOfRange_Index); + } + } + + public void InsertAt(uint index, T value) + { + // Inserting at an index one past the end of the list is equivalent to appending + // so we need to ensure that we're within (0, count + 1). + EnsureIndexInt32(index, _list.Count + 1); + + try + { + _list.Insert((int)index, value); + } + catch (ArgumentOutOfRangeException ex) + { + // Change error code to match what WinRT expects + ex.SetHResult(ExceptionHelpers.E_BOUNDS); + throw; + } + } + + public void RemoveAt(uint index) + { + EnsureIndexInt32(index, _list.Count); + + try + { + _list.RemoveAt((int)index); + } + catch (ArgumentOutOfRangeException ex) + { + // Change error code to match what WinRT expects + ex.SetHResult(ExceptionHelpers.E_BOUNDS); + throw; + } + } + + public void Append(T value) + { + _list.Add(value); + } + + public void RemoveAtEnd() + { + if (_list.Count == 0) + { + Exception e = new InvalidOperationException(ErrorStrings.InvalidOperation_CannotRemoveLastFromEmptyCollection); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + + uint size = (uint)_list.Count; + RemoveAt(size - 1); + } + + public void _Clear() + { + _list.Clear(); + } + + public uint GetMany(uint startIndex, ref T[] items) + { + return GetManyHelper(_list, startIndex, items); + } + + public void ReplaceAll(T[] items) + { + _list.Clear(); + + if (items != null) + { + foreach (T item in items) + { + _list.Add(item); + } + } + } + + private static uint GetManyHelper(global::System.Collections.Generic.IList sourceList, uint startIndex, T[] items) + { + // Calling GetMany with a start index equal to the size of the list should always + // return 0 elements, regardless of the input item size + if (startIndex == sourceList.Count) + { + return 0; + } + + EnsureIndexInt32(startIndex, sourceList.Count); + + if (items == null) + { + return 0; + } + + uint itemCount = Math.Min((uint)items.Length, (uint)sourceList.Count - startIndex); + for (uint i = 0; i < itemCount; ++i) + { + items[i] = sourceList[(int)(i + startIndex)]; + } + + if (typeof(T) == typeof(string)) + { + string[] stringItems = (items as string[])!; + + // Fill in rest of the array with string.Empty to avoid marshaling failure + for (uint i = itemCount; i < items.Length; ++i) + stringItems[i] = string.Empty; + } + + return itemCount; + } + } + + [Guid("913337E9-11A1-4345-A3A2-4E7F956E222D")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate GetAt_0; + internal _get_PropertyAsUInt32 get_Size_1; + public IList_Delegates.GetView_2 GetView_2; + public global::System.Delegate IndexOf_3; + public global::System.Delegate SetAt_4; + public global::System.Delegate InsertAt_5; + public IList_Delegates.RemoveAt_6 RemoveAt_6; + public global::System.Delegate Append_7; + public IList_Delegates.RemoveAtEnd_8 RemoveAtEnd_8; + public IList_Delegates.Clear_9 Clear_9; + public IList_Delegates.GetMany_10 GetMany_10; + public IList_Delegates.ReplaceAll_11 ReplaceAll_11; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IList)); + private static readonly Type GetAt_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), typeof(uint), Marshaler.AbiType.MakeByRefType(), typeof(int) }); + private static readonly Type IndexOf_3_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(uint).MakeByRefType(), typeof(byte).MakeByRefType(), typeof(int) }); + private static readonly Type SetAt_4_Type = Expression.GetDelegateType(new Type[] { typeof(void*), typeof(uint), Marshaler.AbiType, typeof(int) }); + private static readonly Type InsertAt_5_Type = Expression.GetDelegateType(new Type[] { typeof(void*), typeof(uint), Marshaler.AbiType, typeof(int) }); + private static readonly Type Append_7_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + GetAt_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], GetAt_0_Type); + get_Size_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsUInt32>(vftbl[7]); + GetView_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8]); + IndexOf_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9], IndexOf_3_Type); + SetAt_4 = Marshal.GetDelegateForFunctionPointer(vftbl[10], SetAt_4_Type); + InsertAt_5 = Marshal.GetDelegateForFunctionPointer(vftbl[11], InsertAt_5_Type); + RemoveAt_6 = Marshal.GetDelegateForFunctionPointer(vftbl[12]); + Append_7 = Marshal.GetDelegateForFunctionPointer(vftbl[13], Append_7_Type); + RemoveAtEnd_8 = Marshal.GetDelegateForFunctionPointer(vftbl[14]); + Clear_9 = Marshal.GetDelegateForFunctionPointer(vftbl[15]); + GetMany_10 = Marshal.GetDelegateForFunctionPointer(vftbl[16]); + ReplaceAll_11 = Marshal.GetDelegateForFunctionPointer(vftbl[17]); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + GetAt_0 = global::System.Delegate.CreateDelegate(GetAt_0_Type, typeof(Vftbl).GetMethod("Do_Abi_GetAt_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + get_Size_1 = Do_Abi_get_Size_1, + GetView_2 = Do_Abi_GetView_2, + IndexOf_3 = global::System.Delegate.CreateDelegate(IndexOf_3_Type, typeof(Vftbl).GetMethod("Do_Abi_IndexOf_3", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + SetAt_4 = global::System.Delegate.CreateDelegate(SetAt_4_Type, typeof(Vftbl).GetMethod("Do_Abi_SetAt_4", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + InsertAt_5 = global::System.Delegate.CreateDelegate(InsertAt_5_Type, typeof(Vftbl).GetMethod("Do_Abi_InsertAt_5", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + RemoveAt_6 = Do_Abi_RemoveAt_6, + Append_7 = global::System.Delegate.CreateDelegate(Append_7_Type, typeof(Vftbl).GetMethod("Do_Abi_Append_7", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + RemoveAtEnd_8 = Do_Abi_RemoveAtEnd_8, + Clear_9 = Do_Abi_Clear_9, + GetMany_10 = Do_Abi_GetMany_10, + ReplaceAll_11 = Do_Abi_ReplaceAll_11 + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 12); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetAt_0); + nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Size_1); + nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetView_2); + nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.IndexOf_3); + nativeVftbl[10] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.SetAt_4); + nativeVftbl[11] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.InsertAt_5); + nativeVftbl[12] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.RemoveAt_6); + nativeVftbl[13] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Append_7); + nativeVftbl[14] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.RemoveAtEnd_8); + nativeVftbl[15] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Clear_9); + nativeVftbl[16] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetMany_10); + nativeVftbl[17] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.ReplaceAll_11); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable, ToAbiHelper> _adapterTable = + new ConditionalWeakTable, ToAbiHelper>(); + + private static global::Windows.Foundation.Collections.IVector FindAdapter(IntPtr thisPtr) + { + var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); + return _adapterTable.GetValue(__this, (list) => new ToAbiHelper(list)); + } + + private static unsafe int Do_Abi_GetAt_0(void* thisPtr, uint index, out TAbi __return_value__) + { + T ____return_value__ = default; + __return_value__ = default; + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).GetAt(index); + __return_value__ = (TAbi)Marshaler.FromManaged(____return_value__); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_GetView_2(IntPtr thisPtr, out IntPtr __return_value__) + { + global::Windows.Foundation.Collections.IVectorView ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).GetView(); + __return_value__ = MarshalInterface>.FromManaged(____return_value__); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_IndexOf_3(void* thisPtr, TAbi value, out uint index, out byte __return_value__) + { + bool ____return_value__ = default; + + index = default; + __return_value__ = default; + uint __index = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).IndexOf(Marshaler.FromAbi(value), out __index); index = __index; + __return_value__ = (byte)(____return_value__ ? 1 : 0); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_SetAt_4(void* thisPtr, uint index, TAbi value) + { + try + { + FindAdapter(new IntPtr(thisPtr)).SetAt(index, Marshaler.FromAbi(value)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_InsertAt_5(void* thisPtr, uint index, TAbi value) + { + + + try + { + FindAdapter(new IntPtr(thisPtr)).InsertAt(index, Marshaler.FromAbi(value)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_RemoveAt_6(IntPtr thisPtr, uint index) + { + try + { + FindAdapter(thisPtr).RemoveAt(index); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_Append_7(void* thisPtr, TAbi value) + { + try + { + FindAdapter(new IntPtr(thisPtr)).Append(Marshaler.FromAbi(value)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_RemoveAtEnd_8(IntPtr thisPtr) + { + try + { + FindAdapter(thisPtr).RemoveAtEnd(); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_Clear_9(IntPtr thisPtr) + { + try + { + FindAdapter(thisPtr)._Clear(); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_GetMany_10(IntPtr thisPtr, uint startIndex, int __itemsSize, IntPtr items, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + T[] __items = Marshaler.FromAbiArray((__itemsSize, items)); + + try + { + ____return_value__ = FindAdapter(thisPtr).GetMany(startIndex, ref __items); Marshaler.CopyManagedArray(__items, items); + __return_value__ = ____return_value__; + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_ReplaceAll_11(IntPtr thisPtr, int __itemsSize, IntPtr items) + { + try + { + FindAdapter(thisPtr).ReplaceAll(Marshaler.FromAbiArray((__itemsSize, items))); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).Size; + __return_value__ = ____return_value__; + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + public static Guid PIID = Vftbl.PIID; + + private static FromAbiHelper _FromVector(IWinRTObject _this) + { + return (FromAbiHelper)_this.GetOrCreateTypeHelperData(typeof(global::System.Collections.Generic.IList).TypeHandle, + () => new FromAbiHelper((global::Windows.Foundation.Collections.IVector)_this)); + } + + + unsafe T global::Windows.Foundation.Collections.IVector.GetAt(uint index) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + var __params = new object[] { ThisPtr, index, null }; + try + { + _obj.Vftbl.GetAt_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[2]); + } + finally + { + Marshaler.DisposeAbi(__params[2]); + } + } + + unsafe global::Windows.Foundation.Collections.IVectorView global::Windows.Foundation.Collections.IVector.GetView() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetView_2(ThisPtr, out __retval)); + return MarshalInterface>.FromAbi(__retval); + } + finally + { + MarshalInterface>.DisposeAbi(__retval); + } + } + + unsafe bool global::Windows.Foundation.Collections.IVector.IndexOf(T value, out uint index) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + object __value = default; + var __params = new object[] { ThisPtr, null, null, null }; + try + { + __value = Marshaler.CreateMarshaler(value); + __params[1] = Marshaler.GetAbi(__value); + _obj.Vftbl.IndexOf_3.DynamicInvokeAbi(__params); + index = (uint)__params[2]; + return (byte)__params[3] != 0; + } + finally + { + Marshaler.DisposeMarshaler(__value); + } + } + + unsafe void global::Windows.Foundation.Collections.IVector.SetAt(uint index, T value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + object __value = default; + var __params = new object[] { ThisPtr, index, null }; + try + { + __value = Marshaler.CreateMarshaler(value); + __params[2] = Marshaler.GetAbi(__value); + _obj.Vftbl.SetAt_4.DynamicInvokeAbi(__params); + } + finally + { + Marshaler.DisposeMarshaler(__value); + } + } + + unsafe void global::Windows.Foundation.Collections.IVector.InsertAt(uint index, T value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + object __value = default; + var __params = new object[] { ThisPtr, index, null }; + try + { + __value = Marshaler.CreateMarshaler(value); + __params[2] = Marshaler.GetAbi(__value); + _obj.Vftbl.InsertAt_5.DynamicInvokeAbi(__params); + } + finally + { + Marshaler.DisposeMarshaler(__value); + } + } + + unsafe void global::Windows.Foundation.Collections.IVector.RemoveAt(uint index) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RemoveAt_6(ThisPtr, index)); + } + + unsafe void global::Windows.Foundation.Collections.IVector.Append(T value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + object __value = default; + var __params = new object[] { ThisPtr, null }; + try + { + __value = Marshaler.CreateMarshaler(value); + __params[1] = Marshaler.GetAbi(__value); + _obj.Vftbl.Append_7.DynamicInvokeAbi(__params); + } + finally + { + Marshaler.DisposeMarshaler(__value); + } + } + + unsafe void global::Windows.Foundation.Collections.IVector.RemoveAtEnd() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RemoveAtEnd_8(ThisPtr)); + } + + unsafe void global::Windows.Foundation.Collections.IVector._Clear() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Clear_9(ThisPtr)); + } + + unsafe uint global::Windows.Foundation.Collections.IVector.GetMany(uint startIndex, ref T[] items) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + object __items = default; + int __items_length = default; + IntPtr __items_data = default; + uint __retval = default; + try + { + __items = Marshaler.CreateMarshalerArray(items); + (__items_length, __items_data) = Marshaler.GetAbiArray(__items); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetMany_10(ThisPtr, startIndex, __items_length, __items_data, out __retval)); + items = Marshaler.FromAbiArray((__items_length, __items_data)); + return __retval; + } + finally + { + Marshaler.DisposeMarshalerArray(__items); + } + } + + unsafe void global::Windows.Foundation.Collections.IVector.ReplaceAll(T[] items) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + object __items = default; + int __items_length = default; + IntPtr __items_data = default; + try + { + __items = Marshaler.CreateMarshalerArray(items); + (__items_length, __items_data) = Marshaler.GetAbiArray(__items); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.ReplaceAll_11(ThisPtr, __items_length, __items_data)); + } + finally + { + Marshaler.DisposeMarshalerArray(__items); + } + } + + unsafe uint global::Windows.Foundation.Collections.IVector.Size + { + get + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + uint __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, out __retval)); + return __retval; + } + } + + int global::System.Collections.Generic.ICollection.Count => _FromVector((IWinRTObject)this).Count; + bool global::System.Collections.Generic.ICollection.IsReadOnly => _FromVector((IWinRTObject)this).IsReadOnly; + T global::System.Collections.Generic.IList.this[int index] { get => _FromVector((IWinRTObject)this)[index]; set => _FromVector((IWinRTObject)this)[index] = value; } + int global::System.Collections.Generic.IList.IndexOf(T item) => _FromVector((IWinRTObject)this).IndexOf(item); + void global::System.Collections.Generic.IList.Insert(int index, T item) => _FromVector((IWinRTObject)this).Insert(index, item); + void global::System.Collections.Generic.IList.RemoveAt(int index) => _FromVector((IWinRTObject)this).RemoveAt(index); + void global::System.Collections.Generic.ICollection.Add(T item) => _FromVector((IWinRTObject)this).Add(item); + void global::System.Collections.Generic.ICollection.Clear() => _FromVector((IWinRTObject)this).Clear(); + bool global::System.Collections.Generic.ICollection.Contains(T item) => _FromVector((IWinRTObject)this).Contains(item); + void global::System.Collections.Generic.ICollection.CopyTo(T[] array, int arrayIndex) => _FromVector((IWinRTObject)this).CopyTo(array, arrayIndex); + bool global::System.Collections.Generic.ICollection.Remove(T item) => _FromVector((IWinRTObject)this).Remove(item); + 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 + { + public unsafe delegate int GetView_2(IntPtr thisPtr, out IntPtr __return_value__); + public unsafe delegate int RemoveAt_6(IntPtr thisPtr, uint index); + public unsafe delegate int RemoveAtEnd_8(IntPtr thisPtr); + public unsafe delegate int Clear_9(IntPtr thisPtr); + public unsafe delegate int GetMany_10(IntPtr thisPtr, uint startIndex, int __itemsSize, IntPtr items, out uint __return_value__); + public unsafe delegate int ReplaceAll_11(IntPtr thisPtr, int __itemsSize, IntPtr items); + } +} diff --git a/WinRT.Runtime/Projections/IList.cs b/WinRT.Runtime/Projections/IList.netstandard2.0.cs similarity index 97% rename from WinRT.Runtime/Projections/IList.cs rename to WinRT.Runtime/Projections/IList.netstandard2.0.cs index 403ae9ee3..ebee52540 100644 --- a/WinRT.Runtime/Projections/IList.cs +++ b/WinRT.Runtime/Projections/IList.netstandard2.0.cs @@ -1,933 +1,933 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.InteropServices; -using WinRT; -using WinRT.Interop; -using System.Diagnostics; - -#pragma warning disable 0169 // warning CS0169: The field '...' is never used -#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to - -namespace Windows.Foundation.Collections -{ - [Guid("913337E9-11A1-4345-A3A2-4E7F956E222D")] - interface IVector : IIterable - { - T GetAt(uint index); - IVectorView GetView(); - bool IndexOf(T value, out uint index); - void SetAt(uint index, T value); - void InsertAt(uint index, T value); - void RemoveAt(uint index); - void Append(T value); - void RemoveAtEnd(); - void _Clear(); - uint GetMany(uint startIndex, ref T[] items); - void ReplaceAll(T[] items); - uint Size { get; } - } -} - -namespace ABI.System.Collections.Generic -{ - using global::System; - using global::System.Runtime.CompilerServices; - - [Guid("913337E9-11A1-4345-A3A2-4E7F956E222D")] - public 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))); - - public static IntPtr GetAbi(IObjectReference objRef) => - objRef?.ThisPtr ?? IntPtr.Zero; - - public static global::System.Collections.Generic.IList FromAbi(IntPtr thisPtr) => - thisPtr == IntPtr.Zero ? null : new IList(ObjRefFromAbi(thisPtr)); - - public static IntPtr FromManaged(global::System.Collections.Generic.IList value) => - (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); - - public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); - - public static void DisposeAbi(IntPtr abi) => - MarshalInterfaceHelper>.DisposeAbi(abi); - - public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IList)); - - public class FromAbiHelper : global::System.Collections.Generic.IList - { - private readonly global::ABI.System.Collections.Generic.IList _vector; - private readonly global::ABI.System.Collections.Generic.IEnumerable _enumerable; - - public FromAbiHelper(IObjectReference obj) : - this(new global::ABI.System.Collections.Generic.IList(obj)) - { - } - - public FromAbiHelper(global::ABI.System.Collections.Generic.IList vector) - { - _vector = vector; - _enumerable = new ABI.System.Collections.Generic.IEnumerable(vector.ObjRef); - } - - public int Count - { - get - { - uint size = _vector.Size; - if (((uint)int.MaxValue) < size) - { - throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); - } - - return (int)size; - } - } - - public bool IsReadOnly { get => false; } - - public void Add(T item) => _vector.Append(item); - - public void Clear() => _vector._Clear(); - - public bool Contains(T item) => _vector.IndexOf(item, out _); - - public void CopyTo(T[] array, int arrayIndex) - { - if (array == null) - throw new ArgumentNullException(nameof(array)); - - if (arrayIndex < 0) - throw new ArgumentOutOfRangeException(nameof(arrayIndex)); - - if (array.Length <= arrayIndex && Count > 0) - throw new ArgumentException(ErrorStrings.Argument_IndexOutOfArrayBounds); - - if (array.Length - arrayIndex < Count) - throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); - - - int count = Count; - for (int i = 0; i < count; i++) - { - array[i + arrayIndex] = FromAbiHelper.GetAt(_vector, (uint)i); - } - } - - public bool Remove(T item) - { - uint index; - bool exists = _vector.IndexOf(item, out index); - - if (!exists) - return false; - - if (((uint)int.MaxValue) < index) - { - throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); - } - - FromAbiHelper.RemoveAtHelper(_vector, index); - return true; - } - - public T this[int index] { get => Indexer_Get(index); set => Indexer_Set(index, value); } - - private T Indexer_Get(int index) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - return GetAt(_vector, (uint)index); - } - - private void Indexer_Set(int index, T value) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - SetAt(_vector, (uint)index, value); - } - - public int IndexOf(T item) - { - uint index; - bool exists = _vector.IndexOf(item, out index); - - if (!exists) - return -1; - - if (((uint)int.MaxValue) < index) - { - throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); - } - - return (int)index; - } - - public void Insert(int index, T item) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - InsertAtHelper(_vector, (uint)index, item); - } - - public void RemoveAt(int index) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - RemoveAtHelper(_vector, (uint)index); - } - - internal static T GetAt(global::ABI.System.Collections.Generic.IList _this, uint index) - { - try - { - return _this.GetAt(index); - - // We delegate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (ExceptionHelpers.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - - private static void SetAt(global::ABI.System.Collections.Generic.IList _this, uint index, T value) - { - try - { - _this.SetAt(index, value); - - // We deligate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (ExceptionHelpers.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - - private static void InsertAtHelper(global::ABI.System.Collections.Generic.IList _this, uint index, T item) - { - try - { - _this.InsertAt(index, item); - - // We delegate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (ExceptionHelpers.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - - internal static void RemoveAtHelper(global::ABI.System.Collections.Generic.IList _this, uint index) - { - try - { - _this.RemoveAt(index); - - // We delegate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (ExceptionHelpers.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - - public global::System.Collections.Generic.IEnumerator GetEnumerator() => _enumerable.GetEnumerator(); - - global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - } - - public sealed class ToAbiHelper : global::Windows.Foundation.Collections.IVector - { - private global::System.Collections.Generic.IList _list; - - public ToAbiHelper(global::System.Collections.Generic.IList list) => _list = list; - - global::Windows.Foundation.Collections.IIterator global::Windows.Foundation.Collections.IIterable.First() => - new IEnumerator.ToAbiHelper(_list.GetEnumerator()); - - private static void EnsureIndexInt32(uint index, int limit = int.MaxValue) - { - // We use '<=' and not '<' because int.MaxValue == index would imply - // that Size > int.MaxValue: - if (((uint)int.MaxValue) <= index || index >= (uint)limit) - { - Exception e = new ArgumentOutOfRangeException(nameof(index), ErrorStrings.ArgumentOutOfRange_IndexLargerThanMaxValue); - e.SetHResult(ExceptionHelpers.E_BOUNDS); - throw e; - } - } - - public T GetAt(uint index) - { - EnsureIndexInt32(index, _list.Count); - - try - { - return _list[(int)index]; - } - catch (ArgumentOutOfRangeException ex) - { - throw ex.GetExceptionForHR(ExceptionHelpers.E_BOUNDS, ErrorStrings.ArgumentOutOfRange_Index); - } - } - - public uint Size => (uint)_list.Count; - - global::Windows.Foundation.Collections.IVectorView global::Windows.Foundation.Collections.IVector.GetView() - { - // Note: This list is not really read-only - you could QI for a modifiable - // list. We gain some perf by doing this. We believe this is acceptable. - if (!(_list is global::System.Collections.Generic.IReadOnlyList roList)) - { - roList = new ReadOnlyCollection(_list); - } - return new IReadOnlyList.ToAbiHelper(roList); - } - - public bool IndexOf(T value, out uint index) - { - int ind = _list.IndexOf(value); - - if (-1 == ind) - { - index = 0; - return false; - } - - index = (uint)ind; - return true; - } - - public void SetAt(uint index, T value) - { - EnsureIndexInt32(index, _list.Count); - - try - { - _list[(int)index] = value; - } - catch (ArgumentOutOfRangeException ex) - { - throw ex.GetExceptionForHR(ExceptionHelpers.E_BOUNDS, ErrorStrings.ArgumentOutOfRange_Index); - } - } - - public void InsertAt(uint index, T value) - { - // Inserting at an index one past the end of the list is equivalent to appending - // so we need to ensure that we're within (0, count + 1). - EnsureIndexInt32(index, _list.Count + 1); - - try - { - _list.Insert((int)index, value); - } - catch (ArgumentOutOfRangeException ex) - { - // Change error code to match what WinRT expects - ex.SetHResult(ExceptionHelpers.E_BOUNDS); - throw; - } - } - - public void RemoveAt(uint index) - { - EnsureIndexInt32(index, _list.Count); - - try - { - _list.RemoveAt((int)index); - } - catch (ArgumentOutOfRangeException ex) - { - // Change error code to match what WinRT expects - ex.SetHResult(ExceptionHelpers.E_BOUNDS); - throw; - } - } - - public void Append(T value) - { - _list.Add(value); - } - - public void RemoveAtEnd() - { - if (_list.Count == 0) - { - Exception e = new InvalidOperationException(ErrorStrings.InvalidOperation_CannotRemoveLastFromEmptyCollection); - e.SetHResult(ExceptionHelpers.E_BOUNDS); - throw e; - } - - uint size = (uint)_list.Count; - RemoveAt(size - 1); - } - - public void _Clear() - { - _list.Clear(); - } - - public uint GetMany(uint startIndex, ref T[] items) - { - return GetManyHelper(_list, startIndex, items); - } - - public void ReplaceAll(T[] items) - { - _list.Clear(); - - if (items != null) - { - foreach (T item in items) - { - _list.Add(item); - } - } - } - - private static uint GetManyHelper(global::System.Collections.Generic.IList sourceList, uint startIndex, T[] items) - { - // Calling GetMany with a start index equal to the size of the list should always - // return 0 elements, regardless of the input item size - if (startIndex == sourceList.Count) - { - return 0; - } - - EnsureIndexInt32(startIndex, sourceList.Count); - - if (items == null) - { - return 0; - } - - uint itemCount = Math.Min((uint)items.Length, (uint)sourceList.Count - startIndex); - for (uint i = 0; i < itemCount; ++i) - { - items[i] = sourceList[(int)(i + startIndex)]; - } - - if (typeof(T) == typeof(string)) - { - string[] stringItems = (items as string[])!; - - // Fill in rest of the array with string.Empty to avoid marshaling failure - for (uint i = itemCount; i < items.Length; ++i) - stringItems[i] = string.Empty; - } - - return itemCount; - } - } - - [Guid("913337E9-11A1-4345-A3A2-4E7F956E222D")] - public struct Vftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - public global::System.Delegate GetAt_0; - internal _get_PropertyAsUInt32 get_Size_1; - public IList_Delegates.GetView_2 GetView_2; - public global::System.Delegate IndexOf_3; - public global::System.Delegate SetAt_4; - public global::System.Delegate InsertAt_5; - public IList_Delegates.RemoveAt_6 RemoveAt_6; - public global::System.Delegate Append_7; - public IList_Delegates.RemoveAtEnd_8 RemoveAtEnd_8; - public IList_Delegates.Clear_9 Clear_9; - public IList_Delegates.GetMany_10 GetMany_10; - public IList_Delegates.ReplaceAll_11 ReplaceAll_11; - public static Guid PIID = GuidGenerator.CreateIID(typeof(IList)); - private static readonly Type GetAt_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), typeof(uint), Marshaler.AbiType.MakeByRefType(), typeof(int) }); - private static readonly Type IndexOf_3_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(uint).MakeByRefType(), typeof(byte).MakeByRefType(), typeof(int) }); - private static readonly Type SetAt_4_Type = Expression.GetDelegateType(new Type[] { typeof(void*), typeof(uint), Marshaler.AbiType, typeof(int) }); - private static readonly Type InsertAt_5_Type = Expression.GetDelegateType(new Type[] { typeof(void*), typeof(uint), Marshaler.AbiType, typeof(int) }); - private static readonly Type Append_7_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(int) }); - - internal unsafe Vftbl(IntPtr thisPtr) - { - var vftblPtr = Marshal.PtrToStructure(thisPtr); - var vftbl = (IntPtr*)vftblPtr.Vftbl; - IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); - GetAt_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], GetAt_0_Type); - get_Size_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsUInt32>(vftbl[7]); - GetView_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8]); - IndexOf_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9], IndexOf_3_Type); - SetAt_4 = Marshal.GetDelegateForFunctionPointer(vftbl[10], SetAt_4_Type); - InsertAt_5 = Marshal.GetDelegateForFunctionPointer(vftbl[11], InsertAt_5_Type); - RemoveAt_6 = Marshal.GetDelegateForFunctionPointer(vftbl[12]); - Append_7 = Marshal.GetDelegateForFunctionPointer(vftbl[13], Append_7_Type); - RemoveAtEnd_8 = Marshal.GetDelegateForFunctionPointer(vftbl[14]); - Clear_9 = Marshal.GetDelegateForFunctionPointer(vftbl[15]); - GetMany_10 = Marshal.GetDelegateForFunctionPointer(vftbl[16]); - ReplaceAll_11 = Marshal.GetDelegateForFunctionPointer(vftbl[17]); - } - - private static readonly Vftbl AbiToProjectionVftable; - public static readonly IntPtr AbiToProjectionVftablePtr; - static unsafe Vftbl() - { - AbiToProjectionVftable = new Vftbl - { - IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, - GetAt_0 = global::System.Delegate.CreateDelegate(GetAt_0_Type, typeof(Vftbl).GetMethod("Do_Abi_GetAt_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), - get_Size_1 = Do_Abi_get_Size_1, - GetView_2 = Do_Abi_GetView_2, - IndexOf_3 = global::System.Delegate.CreateDelegate(IndexOf_3_Type, typeof(Vftbl).GetMethod("Do_Abi_IndexOf_3", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), - SetAt_4 = global::System.Delegate.CreateDelegate(SetAt_4_Type, typeof(Vftbl).GetMethod("Do_Abi_SetAt_4", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), - InsertAt_5 = global::System.Delegate.CreateDelegate(InsertAt_5_Type, typeof(Vftbl).GetMethod("Do_Abi_InsertAt_5", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), - RemoveAt_6 = Do_Abi_RemoveAt_6, - Append_7 = global::System.Delegate.CreateDelegate(Append_7_Type, typeof(Vftbl).GetMethod("Do_Abi_Append_7", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), - RemoveAtEnd_8 = Do_Abi_RemoveAtEnd_8, - Clear_9 = Do_Abi_Clear_9, - GetMany_10 = Do_Abi_GetMany_10, - ReplaceAll_11 = Do_Abi_ReplaceAll_11 - }; - var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 12); - Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); - nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetAt_0); - nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Size_1); - nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetView_2); - nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.IndexOf_3); - nativeVftbl[10] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.SetAt_4); - nativeVftbl[11] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.InsertAt_5); - nativeVftbl[12] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.RemoveAt_6); - nativeVftbl[13] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Append_7); - nativeVftbl[14] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.RemoveAtEnd_8); - nativeVftbl[15] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Clear_9); - nativeVftbl[16] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetMany_10); - nativeVftbl[17] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.ReplaceAll_11); - - AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; - } - - private static ConditionalWeakTable, ToAbiHelper> _adapterTable = - new ConditionalWeakTable, ToAbiHelper>(); - - private static global::Windows.Foundation.Collections.IVector FindAdapter(IntPtr thisPtr) - { - var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); - return _adapterTable.GetValue(__this, (list) => new ToAbiHelper(list)); - } - - private static unsafe int Do_Abi_GetAt_0(void* thisPtr, uint index, out TAbi __return_value__) - { - T ____return_value__ = default; - __return_value__ = default; - try - { - ____return_value__ = FindAdapter(new IntPtr(thisPtr)).GetAt(index); - __return_value__ = (TAbi)Marshaler.FromManaged(____return_value__); - - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_GetView_2(IntPtr thisPtr, out IntPtr __return_value__) - { - global::Windows.Foundation.Collections.IVectorView ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(thisPtr).GetView(); - __return_value__ = MarshalInterface>.FromManaged(____return_value__); - - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_IndexOf_3(void* thisPtr, TAbi value, out uint index, out byte __return_value__) - { - bool ____return_value__ = default; - - index = default; - __return_value__ = default; - uint __index = default; - - try - { - ____return_value__ = FindAdapter(new IntPtr(thisPtr)).IndexOf(Marshaler.FromAbi(value), out __index); index = __index; - __return_value__ = (byte)(____return_value__ ? 1 : 0); - - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_SetAt_4(void* thisPtr, uint index, TAbi value) - { - try - { - FindAdapter(new IntPtr(thisPtr)).SetAt(index, Marshaler.FromAbi(value)); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_InsertAt_5(void* thisPtr, uint index, TAbi value) - { - - - try - { - FindAdapter(new IntPtr(thisPtr)).InsertAt(index, Marshaler.FromAbi(value)); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_RemoveAt_6(IntPtr thisPtr, uint index) - { - try - { - FindAdapter(thisPtr).RemoveAt(index); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_Append_7(void* thisPtr, TAbi value) - { - try - { - FindAdapter(new IntPtr(thisPtr)).Append(Marshaler.FromAbi(value)); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_RemoveAtEnd_8(IntPtr thisPtr) - { - try - { - FindAdapter(thisPtr).RemoveAtEnd(); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_Clear_9(IntPtr thisPtr) - { - try - { - FindAdapter(thisPtr)._Clear(); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_GetMany_10(IntPtr thisPtr, uint startIndex, int __itemsSize, IntPtr items, out uint __return_value__) - { - uint ____return_value__ = default; - - __return_value__ = default; - T[] __items = Marshaler.FromAbiArray((__itemsSize, items)); - - try - { - ____return_value__ = FindAdapter(thisPtr).GetMany(startIndex, ref __items); Marshaler.CopyManagedArray(__items, items); - __return_value__ = ____return_value__; - - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_ReplaceAll_11(IntPtr thisPtr, int __itemsSize, IntPtr items) - { - try - { - FindAdapter(thisPtr).ReplaceAll(Marshaler.FromAbiArray((__itemsSize, items))); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, out uint __return_value__) - { - uint ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(thisPtr).Size; - __return_value__ = ____return_value__; - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - } - public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) - { - if (thisPtr == IntPtr.Zero) - { - return null; - } - var vftblT = new Vftbl(thisPtr); - return ObjectReference.FromAbi(thisPtr, vftblT); - } - public static Guid PIID = Vftbl.PIID; - - public static implicit operator IList(IObjectReference obj) => (obj != null) ? new IList(obj) : null; - public static implicit operator IList(ObjectReference obj) => (obj != null) ? new IList(obj) : null; - protected readonly ObjectReference _obj; - public IObjectReference ObjRef { get => _obj; } - - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - public IList(IObjectReference obj) : this(obj.As()) { } - public IList(ObjectReference obj) - { - _obj = obj; - _FromVector = new FromAbiHelper(this); - } - FromAbiHelper _FromVector; - - - public unsafe T GetAt(uint index) - { - var __params = new object[] { ThisPtr, index, null }; - try - { - _obj.Vftbl.GetAt_0.DynamicInvokeAbi(__params); - return Marshaler.FromAbi(__params[2]); - } - finally - { - Marshaler.DisposeAbi(__params[2]); - } - } - - internal unsafe global::Windows.Foundation.Collections.IVectorView GetView() - { - IntPtr __retval = default; - try - { - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetView_2(ThisPtr, out __retval)); - return MarshalInterface>.FromAbi(__retval); - } - finally - { - MarshalInterface>.DisposeAbi(__retval); - } - } - - public unsafe bool IndexOf(T value, out uint index) - { - object __value = default; - var __params = new object[] { ThisPtr, null, null, null }; - try - { - __value = Marshaler.CreateMarshaler(value); - __params[1] = Marshaler.GetAbi(__value); - _obj.Vftbl.IndexOf_3.DynamicInvokeAbi(__params); - index = (uint)__params[2]; - return (byte)__params[3] != 0; - } - finally - { - Marshaler.DisposeMarshaler(__value); - } - } - - public unsafe void SetAt(uint index, T value) - { - object __value = default; - var __params = new object[] { ThisPtr, index, null }; - try - { - __value = Marshaler.CreateMarshaler(value); - __params[2] = Marshaler.GetAbi(__value); - _obj.Vftbl.SetAt_4.DynamicInvokeAbi(__params); - } - finally - { - Marshaler.DisposeMarshaler(__value); - } - } - - public unsafe void InsertAt(uint index, T value) - { - object __value = default; - var __params = new object[] { ThisPtr, index, null }; - try - { - __value = Marshaler.CreateMarshaler(value); - __params[2] = Marshaler.GetAbi(__value); - _obj.Vftbl.InsertAt_5.DynamicInvokeAbi(__params); - } - finally - { - Marshaler.DisposeMarshaler(__value); - } - } - - public unsafe void RemoveAt(uint index) - { - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RemoveAt_6(ThisPtr, index)); - } - - public unsafe void Append(T value) - { - object __value = default; - var __params = new object[] { ThisPtr, null }; - try - { - __value = Marshaler.CreateMarshaler(value); - __params[1] = Marshaler.GetAbi(__value); - _obj.Vftbl.Append_7.DynamicInvokeAbi(__params); - } - finally - { - Marshaler.DisposeMarshaler(__value); - } - } - - public unsafe void RemoveAtEnd() - { - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RemoveAtEnd_8(ThisPtr)); - } - - public unsafe void _Clear() - { - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Clear_9(ThisPtr)); - } - - public unsafe uint GetMany(uint startIndex, ref T[] items) - { - object __items = default; - int __items_length = default; - IntPtr __items_data = default; - uint __retval = default; - try - { - __items = Marshaler.CreateMarshalerArray(items); - (__items_length, __items_data) = Marshaler.GetAbiArray(__items); - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetMany_10(ThisPtr, startIndex, __items_length, __items_data, out __retval)); - items = Marshaler.FromAbiArray((__items_length, __items_data)); - return __retval; - } - finally - { - Marshaler.DisposeMarshalerArray(__items); - } - } - - public unsafe void ReplaceAll(T[] items) - { - object __items = default; - int __items_length = default; - IntPtr __items_data = default; - try - { - __items = Marshaler.CreateMarshalerArray(items); - (__items_length, __items_data) = Marshaler.GetAbiArray(__items); - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.ReplaceAll_11(ThisPtr, __items_length, __items_data)); - } - finally - { - Marshaler.DisposeMarshalerArray(__items); - } - } - - public unsafe uint Size - { - get - { - uint __retval = default; - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, out __retval)); - return __retval; - } - } - - public int Count => _FromVector.Count; - public bool IsReadOnly => _FromVector.IsReadOnly; - public T this[int index] { get => _FromVector[index]; set => _FromVector[index] = value; } - public int IndexOf(T item) => _FromVector.IndexOf(item); - public void Insert(int index, T item) => _FromVector.Insert(index, item); - public void RemoveAt(int index) => _FromVector.RemoveAt(index); - public void Add(T item) => _FromVector.Add(item); - public void Clear() => _FromVector.Clear(); - public bool Contains(T item) => _FromVector.Contains(item); - public void CopyTo(T[] array, int arrayIndex) => _FromVector.CopyTo(array, arrayIndex); - public bool Remove(T item) => _FromVector.Remove(item); - public global::System.Collections.Generic.IEnumerator GetEnumerator() => _FromVector.GetEnumerator(); - IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - } - public 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); - public unsafe delegate int RemoveAtEnd_8(IntPtr thisPtr); - public unsafe delegate int Clear_9(IntPtr thisPtr); - public unsafe delegate int GetMany_10(IntPtr thisPtr, uint startIndex, int __itemsSize, IntPtr items, out uint __return_value__); - public unsafe delegate int ReplaceAll_11(IntPtr thisPtr, int __itemsSize, IntPtr items); - } -} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; +using System.Diagnostics; + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Windows.Foundation.Collections +{ + [Guid("913337E9-11A1-4345-A3A2-4E7F956E222D")] + interface IVector : IIterable + { + T GetAt(uint index); + IVectorView GetView(); + bool IndexOf(T value, out uint index); + void SetAt(uint index, T value); + void InsertAt(uint index, T value); + void RemoveAt(uint index); + void Append(T value); + void RemoveAtEnd(); + void _Clear(); + uint GetMany(uint startIndex, ref T[] items); + void ReplaceAll(T[] items); + uint Size { get; } + } +} + +namespace ABI.System.Collections.Generic +{ + using global::System; + using global::System.Runtime.CompilerServices; + + [Guid("913337E9-11A1-4345-A3A2-4E7F956E222D")] + public 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))); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static global::System.Collections.Generic.IList FromAbi(IntPtr thisPtr) => + thisPtr == IntPtr.Zero ? null : new IList(ObjRefFromAbi(thisPtr)); + + public static IntPtr FromManaged(global::System.Collections.Generic.IList value) => + (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); + + public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IList)); + + public class FromAbiHelper : global::System.Collections.Generic.IList + { + private readonly global::ABI.System.Collections.Generic.IList _vector; + private readonly global::ABI.System.Collections.Generic.IEnumerable _enumerable; + + public FromAbiHelper(IObjectReference obj) : + this(new global::ABI.System.Collections.Generic.IList(obj)) + { + } + + public FromAbiHelper(global::ABI.System.Collections.Generic.IList vector) + { + _vector = vector; + _enumerable = new ABI.System.Collections.Generic.IEnumerable(vector.ObjRef); + } + + public int Count + { + get + { + uint size = _vector.Size; + if (((uint)int.MaxValue) < size) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); + } + + return (int)size; + } + } + + public bool IsReadOnly { get => false; } + + public void Add(T item) => _vector.Append(item); + + public void Clear() => _vector._Clear(); + + public bool Contains(T item) => _vector.IndexOf(item, out _); + + public void CopyTo(T[] array, int arrayIndex) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + + if (arrayIndex < 0) + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); + + if (array.Length <= arrayIndex && Count > 0) + throw new ArgumentException(ErrorStrings.Argument_IndexOutOfArrayBounds); + + if (array.Length - arrayIndex < Count) + throw new ArgumentException(ErrorStrings.Argument_InsufficientSpaceToCopyCollection); + + + int count = Count; + for (int i = 0; i < count; i++) + { + array[i + arrayIndex] = FromAbiHelper.GetAt(_vector, (uint)i); + } + } + + public bool Remove(T item) + { + uint index; + bool exists = _vector.IndexOf(item, out index); + + if (!exists) + return false; + + if (((uint)int.MaxValue) < index) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); + } + + FromAbiHelper.RemoveAtHelper(_vector, index); + return true; + } + + public T this[int index] { get => Indexer_Get(index); set => Indexer_Set(index, value); } + + private T Indexer_Get(int index) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + return GetAt(_vector, (uint)index); + } + + private void Indexer_Set(int index, T value) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + SetAt(_vector, (uint)index, value); + } + + public int IndexOf(T item) + { + uint index; + bool exists = _vector.IndexOf(item, out index); + + if (!exists) + return -1; + + if (((uint)int.MaxValue) < index) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); + } + + return (int)index; + } + + public void Insert(int index, T item) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + InsertAtHelper(_vector, (uint)index, item); + } + + public void RemoveAt(int index) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + RemoveAtHelper(_vector, (uint)index); + } + + internal static T GetAt(global::ABI.System.Collections.Generic.IList _this, uint index) + { + try + { + return _this.GetAt(index); + + // We delegate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + + throw; + } + } + + private static void SetAt(global::ABI.System.Collections.Generic.IList _this, uint index, T value) + { + try + { + _this.SetAt(index, value); + + // We deligate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + + throw; + } + } + + private static void InsertAtHelper(global::ABI.System.Collections.Generic.IList _this, uint index, T item) + { + try + { + _this.InsertAt(index, item); + + // We delegate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + + throw; + } + } + + internal static void RemoveAtHelper(global::ABI.System.Collections.Generic.IList _this, uint index) + { + try + { + _this.RemoveAt(index); + + // We delegate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + + throw; + } + } + + public global::System.Collections.Generic.IEnumerator GetEnumerator() => _enumerable.GetEnumerator(); + + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + + public sealed class ToAbiHelper : global::Windows.Foundation.Collections.IVector + { + private global::System.Collections.Generic.IList _list; + + public ToAbiHelper(global::System.Collections.Generic.IList list) => _list = list; + + global::Windows.Foundation.Collections.IIterator global::Windows.Foundation.Collections.IIterable.First() => + new IEnumerator.ToAbiHelper(_list.GetEnumerator()); + + private static void EnsureIndexInt32(uint index, int limit = int.MaxValue) + { + // We use '<=' and not '<' because int.MaxValue == index would imply + // that Size > int.MaxValue: + if (((uint)int.MaxValue) <= index || index >= (uint)limit) + { + Exception e = new ArgumentOutOfRangeException(nameof(index), ErrorStrings.ArgumentOutOfRange_IndexLargerThanMaxValue); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + } + + public T GetAt(uint index) + { + EnsureIndexInt32(index, _list.Count); + + try + { + return _list[(int)index]; + } + catch (ArgumentOutOfRangeException ex) + { + throw ex.GetExceptionForHR(ExceptionHelpers.E_BOUNDS, ErrorStrings.ArgumentOutOfRange_Index); + } + } + + public uint Size => (uint)_list.Count; + + global::Windows.Foundation.Collections.IVectorView global::Windows.Foundation.Collections.IVector.GetView() + { + // Note: This list is not really read-only - you could QI for a modifiable + // list. We gain some perf by doing this. We believe this is acceptable. + if (!(_list is global::System.Collections.Generic.IReadOnlyList roList)) + { + roList = new ReadOnlyCollection(_list); + } + return new IReadOnlyList.ToAbiHelper(roList); + } + + public bool IndexOf(T value, out uint index) + { + int ind = _list.IndexOf(value); + + if (-1 == ind) + { + index = 0; + return false; + } + + index = (uint)ind; + return true; + } + + public void SetAt(uint index, T value) + { + EnsureIndexInt32(index, _list.Count); + + try + { + _list[(int)index] = value; + } + catch (ArgumentOutOfRangeException ex) + { + throw ex.GetExceptionForHR(ExceptionHelpers.E_BOUNDS, ErrorStrings.ArgumentOutOfRange_Index); + } + } + + public void InsertAt(uint index, T value) + { + // Inserting at an index one past the end of the list is equivalent to appending + // so we need to ensure that we're within (0, count + 1). + EnsureIndexInt32(index, _list.Count + 1); + + try + { + _list.Insert((int)index, value); + } + catch (ArgumentOutOfRangeException ex) + { + // Change error code to match what WinRT expects + ex.SetHResult(ExceptionHelpers.E_BOUNDS); + throw; + } + } + + public void RemoveAt(uint index) + { + EnsureIndexInt32(index, _list.Count); + + try + { + _list.RemoveAt((int)index); + } + catch (ArgumentOutOfRangeException ex) + { + // Change error code to match what WinRT expects + ex.SetHResult(ExceptionHelpers.E_BOUNDS); + throw; + } + } + + public void Append(T value) + { + _list.Add(value); + } + + public void RemoveAtEnd() + { + if (_list.Count == 0) + { + Exception e = new InvalidOperationException(ErrorStrings.InvalidOperation_CannotRemoveLastFromEmptyCollection); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + + uint size = (uint)_list.Count; + RemoveAt(size - 1); + } + + public void _Clear() + { + _list.Clear(); + } + + public uint GetMany(uint startIndex, ref T[] items) + { + return GetManyHelper(_list, startIndex, items); + } + + public void ReplaceAll(T[] items) + { + _list.Clear(); + + if (items != null) + { + foreach (T item in items) + { + _list.Add(item); + } + } + } + + private static uint GetManyHelper(global::System.Collections.Generic.IList sourceList, uint startIndex, T[] items) + { + // Calling GetMany with a start index equal to the size of the list should always + // return 0 elements, regardless of the input item size + if (startIndex == sourceList.Count) + { + return 0; + } + + EnsureIndexInt32(startIndex, sourceList.Count); + + if (items == null) + { + return 0; + } + + uint itemCount = Math.Min((uint)items.Length, (uint)sourceList.Count - startIndex); + for (uint i = 0; i < itemCount; ++i) + { + items[i] = sourceList[(int)(i + startIndex)]; + } + + if (typeof(T) == typeof(string)) + { + string[] stringItems = (items as string[])!; + + // Fill in rest of the array with string.Empty to avoid marshaling failure + for (uint i = itemCount; i < items.Length; ++i) + stringItems[i] = string.Empty; + } + + return itemCount; + } + } + + [Guid("913337E9-11A1-4345-A3A2-4E7F956E222D")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate GetAt_0; + internal _get_PropertyAsUInt32 get_Size_1; + public IList_Delegates.GetView_2 GetView_2; + public global::System.Delegate IndexOf_3; + public global::System.Delegate SetAt_4; + public global::System.Delegate InsertAt_5; + public IList_Delegates.RemoveAt_6 RemoveAt_6; + public global::System.Delegate Append_7; + public IList_Delegates.RemoveAtEnd_8 RemoveAtEnd_8; + public IList_Delegates.Clear_9 Clear_9; + public IList_Delegates.GetMany_10 GetMany_10; + public IList_Delegates.ReplaceAll_11 ReplaceAll_11; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IList)); + private static readonly Type GetAt_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), typeof(uint), Marshaler.AbiType.MakeByRefType(), typeof(int) }); + private static readonly Type IndexOf_3_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(uint).MakeByRefType(), typeof(byte).MakeByRefType(), typeof(int) }); + private static readonly Type SetAt_4_Type = Expression.GetDelegateType(new Type[] { typeof(void*), typeof(uint), Marshaler.AbiType, typeof(int) }); + private static readonly Type InsertAt_5_Type = Expression.GetDelegateType(new Type[] { typeof(void*), typeof(uint), Marshaler.AbiType, typeof(int) }); + private static readonly Type Append_7_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + GetAt_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], GetAt_0_Type); + get_Size_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsUInt32>(vftbl[7]); + GetView_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8]); + IndexOf_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9], IndexOf_3_Type); + SetAt_4 = Marshal.GetDelegateForFunctionPointer(vftbl[10], SetAt_4_Type); + InsertAt_5 = Marshal.GetDelegateForFunctionPointer(vftbl[11], InsertAt_5_Type); + RemoveAt_6 = Marshal.GetDelegateForFunctionPointer(vftbl[12]); + Append_7 = Marshal.GetDelegateForFunctionPointer(vftbl[13], Append_7_Type); + RemoveAtEnd_8 = Marshal.GetDelegateForFunctionPointer(vftbl[14]); + Clear_9 = Marshal.GetDelegateForFunctionPointer(vftbl[15]); + GetMany_10 = Marshal.GetDelegateForFunctionPointer(vftbl[16]); + ReplaceAll_11 = Marshal.GetDelegateForFunctionPointer(vftbl[17]); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + GetAt_0 = global::System.Delegate.CreateDelegate(GetAt_0_Type, typeof(Vftbl).GetMethod("Do_Abi_GetAt_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + get_Size_1 = Do_Abi_get_Size_1, + GetView_2 = Do_Abi_GetView_2, + IndexOf_3 = global::System.Delegate.CreateDelegate(IndexOf_3_Type, typeof(Vftbl).GetMethod("Do_Abi_IndexOf_3", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + SetAt_4 = global::System.Delegate.CreateDelegate(SetAt_4_Type, typeof(Vftbl).GetMethod("Do_Abi_SetAt_4", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + InsertAt_5 = global::System.Delegate.CreateDelegate(InsertAt_5_Type, typeof(Vftbl).GetMethod("Do_Abi_InsertAt_5", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + RemoveAt_6 = Do_Abi_RemoveAt_6, + Append_7 = global::System.Delegate.CreateDelegate(Append_7_Type, typeof(Vftbl).GetMethod("Do_Abi_Append_7", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + RemoveAtEnd_8 = Do_Abi_RemoveAtEnd_8, + Clear_9 = Do_Abi_Clear_9, + GetMany_10 = Do_Abi_GetMany_10, + ReplaceAll_11 = Do_Abi_ReplaceAll_11 + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 12); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetAt_0); + nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Size_1); + nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetView_2); + nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.IndexOf_3); + nativeVftbl[10] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.SetAt_4); + nativeVftbl[11] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.InsertAt_5); + nativeVftbl[12] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.RemoveAt_6); + nativeVftbl[13] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Append_7); + nativeVftbl[14] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.RemoveAtEnd_8); + nativeVftbl[15] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Clear_9); + nativeVftbl[16] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetMany_10); + nativeVftbl[17] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.ReplaceAll_11); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable, ToAbiHelper> _adapterTable = + new ConditionalWeakTable, ToAbiHelper>(); + + private static global::Windows.Foundation.Collections.IVector FindAdapter(IntPtr thisPtr) + { + var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); + return _adapterTable.GetValue(__this, (list) => new ToAbiHelper(list)); + } + + private static unsafe int Do_Abi_GetAt_0(void* thisPtr, uint index, out TAbi __return_value__) + { + T ____return_value__ = default; + __return_value__ = default; + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).GetAt(index); + __return_value__ = (TAbi)Marshaler.FromManaged(____return_value__); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_GetView_2(IntPtr thisPtr, out IntPtr __return_value__) + { + global::Windows.Foundation.Collections.IVectorView ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).GetView(); + __return_value__ = MarshalInterface>.FromManaged(____return_value__); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_IndexOf_3(void* thisPtr, TAbi value, out uint index, out byte __return_value__) + { + bool ____return_value__ = default; + + index = default; + __return_value__ = default; + uint __index = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).IndexOf(Marshaler.FromAbi(value), out __index); index = __index; + __return_value__ = (byte)(____return_value__ ? 1 : 0); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_SetAt_4(void* thisPtr, uint index, TAbi value) + { + try + { + FindAdapter(new IntPtr(thisPtr)).SetAt(index, Marshaler.FromAbi(value)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_InsertAt_5(void* thisPtr, uint index, TAbi value) + { + + + try + { + FindAdapter(new IntPtr(thisPtr)).InsertAt(index, Marshaler.FromAbi(value)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_RemoveAt_6(IntPtr thisPtr, uint index) + { + try + { + FindAdapter(thisPtr).RemoveAt(index); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_Append_7(void* thisPtr, TAbi value) + { + try + { + FindAdapter(new IntPtr(thisPtr)).Append(Marshaler.FromAbi(value)); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_RemoveAtEnd_8(IntPtr thisPtr) + { + try + { + FindAdapter(thisPtr).RemoveAtEnd(); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_Clear_9(IntPtr thisPtr) + { + try + { + FindAdapter(thisPtr)._Clear(); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_GetMany_10(IntPtr thisPtr, uint startIndex, int __itemsSize, IntPtr items, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + T[] __items = Marshaler.FromAbiArray((__itemsSize, items)); + + try + { + ____return_value__ = FindAdapter(thisPtr).GetMany(startIndex, ref __items); Marshaler.CopyManagedArray(__items, items); + __return_value__ = ____return_value__; + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_ReplaceAll_11(IntPtr thisPtr, int __itemsSize, IntPtr items) + { + try + { + FindAdapter(thisPtr).ReplaceAll(Marshaler.FromAbiArray((__itemsSize, items))); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).Size; + __return_value__ = ____return_value__; + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + public static Guid PIID = Vftbl.PIID; + + public static implicit operator IList(IObjectReference obj) => (obj != null) ? new IList(obj) : null; + public static implicit operator IList(ObjectReference obj) => (obj != null) ? new IList(obj) : null; + protected readonly ObjectReference _obj; + public IObjectReference ObjRef { get => _obj; } + + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public IList(IObjectReference obj) : this(obj.As()) { } + public IList(ObjectReference obj) + { + _obj = obj; + _FromVector = new FromAbiHelper(this); + } + FromAbiHelper _FromVector; + + + public unsafe T GetAt(uint index) + { + var __params = new object[] { ThisPtr, index, null }; + try + { + _obj.Vftbl.GetAt_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[2]); + } + finally + { + Marshaler.DisposeAbi(__params[2]); + } + } + + internal unsafe global::Windows.Foundation.Collections.IVectorView GetView() + { + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetView_2(ThisPtr, out __retval)); + return MarshalInterface>.FromAbi(__retval); + } + finally + { + MarshalInterface>.DisposeAbi(__retval); + } + } + + public unsafe bool IndexOf(T value, out uint index) + { + object __value = default; + var __params = new object[] { ThisPtr, null, null, null }; + try + { + __value = Marshaler.CreateMarshaler(value); + __params[1] = Marshaler.GetAbi(__value); + _obj.Vftbl.IndexOf_3.DynamicInvokeAbi(__params); + index = (uint)__params[2]; + return (byte)__params[3] != 0; + } + finally + { + Marshaler.DisposeMarshaler(__value); + } + } + + public unsafe void SetAt(uint index, T value) + { + object __value = default; + var __params = new object[] { ThisPtr, index, null }; + try + { + __value = Marshaler.CreateMarshaler(value); + __params[2] = Marshaler.GetAbi(__value); + _obj.Vftbl.SetAt_4.DynamicInvokeAbi(__params); + } + finally + { + Marshaler.DisposeMarshaler(__value); + } + } + + public unsafe void InsertAt(uint index, T value) + { + object __value = default; + var __params = new object[] { ThisPtr, index, null }; + try + { + __value = Marshaler.CreateMarshaler(value); + __params[2] = Marshaler.GetAbi(__value); + _obj.Vftbl.InsertAt_5.DynamicInvokeAbi(__params); + } + finally + { + Marshaler.DisposeMarshaler(__value); + } + } + + public unsafe void RemoveAt(uint index) + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RemoveAt_6(ThisPtr, index)); + } + + public unsafe void Append(T value) + { + object __value = default; + var __params = new object[] { ThisPtr, null }; + try + { + __value = Marshaler.CreateMarshaler(value); + __params[1] = Marshaler.GetAbi(__value); + _obj.Vftbl.Append_7.DynamicInvokeAbi(__params); + } + finally + { + Marshaler.DisposeMarshaler(__value); + } + } + + public unsafe void RemoveAtEnd() + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.RemoveAtEnd_8(ThisPtr)); + } + + public unsafe void _Clear() + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Clear_9(ThisPtr)); + } + + public unsafe uint GetMany(uint startIndex, ref T[] items) + { + object __items = default; + int __items_length = default; + IntPtr __items_data = default; + uint __retval = default; + try + { + __items = Marshaler.CreateMarshalerArray(items); + (__items_length, __items_data) = Marshaler.GetAbiArray(__items); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetMany_10(ThisPtr, startIndex, __items_length, __items_data, out __retval)); + items = Marshaler.FromAbiArray((__items_length, __items_data)); + return __retval; + } + finally + { + Marshaler.DisposeMarshalerArray(__items); + } + } + + public unsafe void ReplaceAll(T[] items) + { + object __items = default; + int __items_length = default; + IntPtr __items_data = default; + try + { + __items = Marshaler.CreateMarshalerArray(items); + (__items_length, __items_data) = Marshaler.GetAbiArray(__items); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.ReplaceAll_11(ThisPtr, __items_length, __items_data)); + } + finally + { + Marshaler.DisposeMarshalerArray(__items); + } + } + + public unsafe uint Size + { + get + { + uint __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, out __retval)); + return __retval; + } + } + + public int Count => _FromVector.Count; + public bool IsReadOnly => _FromVector.IsReadOnly; + public T this[int index] { get => _FromVector[index]; set => _FromVector[index] = value; } + public int IndexOf(T item) => _FromVector.IndexOf(item); + public void Insert(int index, T item) => _FromVector.Insert(index, item); + public void RemoveAt(int index) => _FromVector.RemoveAt(index); + public void Add(T item) => _FromVector.Add(item); + public void Clear() => _FromVector.Clear(); + public bool Contains(T item) => _FromVector.Contains(item); + public void CopyTo(T[] array, int arrayIndex) => _FromVector.CopyTo(array, arrayIndex); + public bool Remove(T item) => _FromVector.Remove(item); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => _FromVector.GetEnumerator(); + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + public 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); + public unsafe delegate int RemoveAtEnd_8(IntPtr thisPtr); + public unsafe delegate int Clear_9(IntPtr thisPtr); + public unsafe delegate int GetMany_10(IntPtr thisPtr, uint startIndex, int __itemsSize, IntPtr items, out uint __return_value__); + public unsafe delegate int ReplaceAll_11(IntPtr thisPtr, int __itemsSize, IntPtr items); + } +} diff --git a/WinRT.Runtime/Projections/INotifyCollectionChanged.net5.cs b/WinRT.Runtime/Projections/INotifyCollectionChanged.net5.cs new file mode 100644 index 000000000..c0f589cf0 --- /dev/null +++ b/WinRT.Runtime/Projections/INotifyCollectionChanged.net5.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; +using WinRT; +using WinRT.Interop; + +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")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + + private delegate* _add_CollectionChanged_0; + public delegate* stdcall add_CollectionChanged_0 { get => (delegate* stdcall)_add_CollectionChanged_0; set => _add_CollectionChanged_0=(delegate*)value; } + private delegate* _remove_CollectionChanged_1; + public delegate* stdcall remove_CollectionChanged_1 { get => (delegate* stdcall)_remove_CollectionChanged_1; set => _remove_CollectionChanged_1=(delegate*)value; } + + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + _add_CollectionChanged_0 = &Do_Abi_add_CollectionChanged_0, + _remove_CollectionChanged_1 = &Do_Abi_remove_CollectionChanged_1, + + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 2); + Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static global::System.Runtime.CompilerServices.ConditionalWeakTable> _CollectionChanged_TokenTables = new global::System.Runtime.CompilerServices.ConditionalWeakTable>(); + private static unsafe int Do_Abi_add_CollectionChanged_0(IntPtr thisPtr, IntPtr handler, out global::WinRT.EventRegistrationToken token) + { + token = default; + try + { + var __this = global::WinRT.ComWrappersSupport.FindObject(thisPtr); + var __handler = global::ABI.System.Collections.Specialized.NotifyCollectionChangedEventHandler.FromAbi(handler); + token = _CollectionChanged_TokenTables.GetOrCreateValue(__this).AddEventHandler(__handler); + __this.CollectionChanged += __handler; + return 0; + } + catch (global::System.Exception __ex) + { + return __ex.HResult; + } + } + private static unsafe int Do_Abi_remove_CollectionChanged_1(IntPtr thisPtr, global::WinRT.EventRegistrationToken token) + { + try + { + var __this = global::WinRT.ComWrappersSupport.FindObject(thisPtr); + if (_CollectionChanged_TokenTables.TryGetValue(__this, out var __table) && __table.RemoveEventHandler(token, out var __handler)) + { + __this.CollectionChanged -= __handler; + } + return 0; + } + catch (global::System.Exception __ex) + { + return __ex.HResult; + } + } + } + internal static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + private static EventSource _CollectionChanged(IWinRTObject _this) + { + var _obj = ((ObjectReference)((IWinRTObject)_this).GetObjectReferenceForType(typeof(global::System.Collections.Specialized.INotifyCollectionChanged).TypeHandle)); + + return (EventSource)_this.GetOrCreateTypeHelperData(typeof(global::System.Collections.Specialized.INotifyCollectionChanged).TypeHandle, + () => new EventSource(_obj, _obj.Vftbl.add_CollectionChanged_0, _obj.Vftbl.remove_CollectionChanged_1)); + } + + event global::System.Collections.Specialized.NotifyCollectionChangedEventHandler global::System.Collections.Specialized.INotifyCollectionChanged.CollectionChanged + { + add => _CollectionChanged((IWinRTObject)this).Subscribe(value); + remove => _CollectionChanged((IWinRTObject)this).Unsubscribe(value); + } + + } +} diff --git a/WinRT.Runtime/Projections/INotifyCollectionChanged.cs b/WinRT.Runtime/Projections/INotifyCollectionChanged.netstandard2.0.cs similarity index 83% rename from WinRT.Runtime/Projections/INotifyCollectionChanged.cs rename to WinRT.Runtime/Projections/INotifyCollectionChanged.netstandard2.0.cs index a5a88db1c..db03b7a28 100644 --- a/WinRT.Runtime/Projections/INotifyCollectionChanged.cs +++ b/WinRT.Runtime/Projections/INotifyCollectionChanged.netstandard2.0.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; @@ -16,35 +16,27 @@ public unsafe class INotifyCollectionChanged : global::System.Collections.Specia public struct Vftbl { internal IInspectable.Vftbl IInspectableVftbl; -#if NETSTANDARD2_0 + private void* _add_CollectionChanged_0; public delegate* stdcall add_CollectionChanged_0 { get => (delegate* stdcall)_add_CollectionChanged_0; set => _add_CollectionChanged_0=(void*)value; } private void* _remove_CollectionChanged_1; public delegate* stdcall remove_CollectionChanged_1 { get => (delegate* stdcall)_remove_CollectionChanged_1; set => _remove_CollectionChanged_1=(void*)value; } -#else - private delegate* _add_CollectionChanged_0; - public delegate* stdcall add_CollectionChanged_0 { get => (delegate* stdcall)_add_CollectionChanged_0; set => _add_CollectionChanged_0=(delegate*)value; } - private delegate* _remove_CollectionChanged_1; - public delegate* stdcall remove_CollectionChanged_1 { get => (delegate* stdcall)_remove_CollectionChanged_1; set => _remove_CollectionChanged_1=(delegate*)value; } -#endif + private static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 + private static Delegate[] DelegateCache = new Delegate[2]; -#endif + static unsafe Vftbl() { AbiToProjectionVftable = new Vftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 + _add_CollectionChanged_0 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new _add_EventHandler(Do_Abi_add_CollectionChanged_0)), _remove_CollectionChanged_1 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new _remove_EventHandler(Do_Abi_remove_CollectionChanged_1)), -#else - _add_CollectionChanged_0 = &Do_Abi_add_CollectionChanged_0, - _remove_CollectionChanged_1 = &Do_Abi_remove_CollectionChanged_1, -#endif + }; var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 2); Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); diff --git a/WinRT.Runtime/Projections/INotifyPropertyChanged.net5.cs b/WinRT.Runtime/Projections/INotifyPropertyChanged.net5.cs new file mode 100644 index 000000000..b98825044 --- /dev/null +++ b/WinRT.Runtime/Projections/INotifyPropertyChanged.net5.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using WinRT; +using WinRT.Interop; + +namespace ABI.System.ComponentModel +{ + [DynamicInterfaceCastableImplementation] + [Guid("90B17601-B065-586E-83D9-9ADC3A695284")] + unsafe interface INotifyPropertyChanged : global::System.ComponentModel.INotifyPropertyChanged + { + [Guid("90B17601-B065-586E-83D9-9ADC3A695284")] + [StructLayout(LayoutKind.Sequential)] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + + private delegate* _add_PropertyChanged_0; + public delegate* stdcall add_PropertyChanged_0 { get => (delegate* stdcall)_add_PropertyChanged_0; set => _add_PropertyChanged_0=(delegate*)value; } + private delegate* _remove_PropertyChanged_1; + public delegate* stdcall remove_PropertyChanged_1 { get => (delegate* stdcall)_remove_PropertyChanged_1; set => _remove_PropertyChanged_1=(delegate*)value; } + + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + _add_PropertyChanged_0 = &Do_Abi_add_PropertyChanged_0, + _remove_PropertyChanged_1 = &Do_Abi_remove_PropertyChanged_1, + + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 2); + Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static global::System.Runtime.CompilerServices.ConditionalWeakTable> _PropertyChanged_TokenTables = new global::System.Runtime.CompilerServices.ConditionalWeakTable>(); + + private static unsafe int Do_Abi_add_PropertyChanged_0(IntPtr thisPtr, IntPtr handler, out global::WinRT.EventRegistrationToken token) + { + token = default; + try + { + var __this = global::WinRT.ComWrappersSupport.FindObject(thisPtr); + var __handler = global::ABI.System.ComponentModel.PropertyChangedEventHandler.FromAbi(handler); + token = _PropertyChanged_TokenTables.GetOrCreateValue(__this).AddEventHandler(__handler); + __this.PropertyChanged += __handler; + return 0; + } + catch (global::System.Exception __ex) + { + return __ex.HResult; + } + } + private static unsafe int Do_Abi_remove_PropertyChanged_1(IntPtr thisPtr, global::WinRT.EventRegistrationToken token) + { + try + { + var __this = global::WinRT.ComWrappersSupport.FindObject(thisPtr); + if (_PropertyChanged_TokenTables.TryGetValue(__this, out var __table) && __table.RemoveEventHandler(token, out var __handler)) + { + __this.PropertyChanged -= __handler; + } + return 0; + } + catch (global::System.Exception __ex) + { + return __ex.HResult; + } + } + } + internal static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + private static EventSource _PropertyChanged(IWinRTObject _this) + { + var _obj = (ObjectReference)_this.GetObjectReferenceForType(typeof(global::System.ComponentModel.INotifyPropertyChanged).TypeHandle); + + return (EventSource)_this.GetOrCreateTypeHelperData(typeof(global::System.ComponentModel.INotifyPropertyChanged).TypeHandle, + () => new EventSource(_obj, _obj.Vftbl.add_PropertyChanged_0, _obj.Vftbl.remove_PropertyChanged_1)); + } + + event global::System.ComponentModel.PropertyChangedEventHandler global::System.ComponentModel.INotifyPropertyChanged.PropertyChanged + { + add => _PropertyChanged((IWinRTObject)this).Subscribe(value); + remove => _PropertyChanged((IWinRTObject)this).Unsubscribe(value); + } + + } +} diff --git a/WinRT.Runtime/Projections/INotifyPropertyChanged.cs b/WinRT.Runtime/Projections/INotifyPropertyChanged.netstandard2.0.cs similarity index 83% rename from WinRT.Runtime/Projections/INotifyPropertyChanged.cs rename to WinRT.Runtime/Projections/INotifyPropertyChanged.netstandard2.0.cs index 8fbe9b1c6..59544d53f 100644 --- a/WinRT.Runtime/Projections/INotifyPropertyChanged.cs +++ b/WinRT.Runtime/Projections/INotifyPropertyChanged.netstandard2.0.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; @@ -16,35 +16,27 @@ public unsafe class INotifyPropertyChanged : global::System.ComponentModel.INoti public struct Vftbl { internal IInspectable.Vftbl IInspectableVftbl; -#if NETSTANDARD2_0 + private void* _add_PropertyChanged_0; public delegate* stdcall add_PropertyChanged_0 { get => (delegate* stdcall)_add_PropertyChanged_0; set => _add_PropertyChanged_0=(void*)value; } private void* _remove_PropertyChanged_1; public delegate* stdcall remove_PropertyChanged_1 { get => (delegate* stdcall)_remove_PropertyChanged_1; set => _remove_PropertyChanged_1=(void*)value; } -#else - private delegate* _add_PropertyChanged_0; - public delegate* stdcall add_PropertyChanged_0 { get => (delegate* stdcall)_add_PropertyChanged_0; set => _add_PropertyChanged_0=(delegate*)value; } - private delegate* _remove_PropertyChanged_1; - public delegate* stdcall remove_PropertyChanged_1 { get => (delegate* stdcall)_remove_PropertyChanged_1; set => _remove_PropertyChanged_1=(delegate*)value; } -#endif + private static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 + private static Delegate[] DelegateCache = new Delegate[2]; -#endif + static unsafe Vftbl() { AbiToProjectionVftable = new Vftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 + _add_PropertyChanged_0 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new _add_EventHandler(Do_Abi_add_PropertyChanged_0)), _remove_PropertyChanged_1 = (void*)Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new _remove_EventHandler(Do_Abi_remove_PropertyChanged_1)), -#else - _add_PropertyChanged_0 = &Do_Abi_add_PropertyChanged_0, - _remove_PropertyChanged_1 = &Do_Abi_remove_PropertyChanged_1, -#endif + }; var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(Vftbl), Marshal.SizeOf() + sizeof(IntPtr) * 2); Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); diff --git a/WinRT.Runtime/Projections/IPropertyValue.net5.cs b/WinRT.Runtime/Projections/IPropertyValue.net5.cs new file mode 100644 index 000000000..1dcd179d9 --- /dev/null +++ b/WinRT.Runtime/Projections/IPropertyValue.net5.cs @@ -0,0 +1,1913 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; + +namespace Windows.Foundation +{ + internal enum PropertyType : uint + { + Empty = 0, + UInt8 = 0x1, + Int16 = 0x2, + UInt16 = 0x3, + Int32 = 0x4, + UInt32 = 0x5, + Int64 = 0x6, + UInt64 = 0x7, + Single = 0x8, + Double = 0x9, + Char16 = 0xa, + Boolean = 0xb, + String = 0xc, + Inspectable = 0xd, + DateTime = 0xe, + TimeSpan = 0xf, + Guid = 0x10, + Point = 0x11, + Size = 0x12, + Rect = 0x13, + OtherType = 0x14, + UInt8Array = 0x401, + Int16Array = 0x402, + UInt16Array = 0x403, + Int32Array = 0x404, + UInt32Array = 0x405, + Int64Array = 0x406, + UInt64Array = 0x407, + SingleArray = 0x408, + DoubleArray = 0x409, + Char16Array = 0x40a, + BooleanArray = 0x40b, + StringArray = 0x40c, + InspectableArray = 0x40d, + DateTimeArray = 0x40e, + TimeSpanArray = 0x40f, + GuidArray = 0x410, + PointArray = 0x411, + SizeArray = 0x412, + RectArray = 0x413, + OtherTypeArray = 0x414, + } + + [Guid("4BD682DD-7554-40E9-9A9B-82654EDE7E62")] + internal interface IPropertyValue + { + byte GetUInt8(); + short GetInt16(); + ushort GetUInt16(); + int GetInt32(); + uint GetUInt32(); + long GetInt64(); + ulong GetUInt64(); + float GetSingle(); + double GetDouble(); + char GetChar16(); + bool GetBoolean(); + string GetString(); + Guid GetGuid(); + global::System.DateTimeOffset GetDateTime(); + global::System.TimeSpan GetTimeSpan(); + Point GetPoint(); + Size GetSize(); + Rect GetRect(); + void GetUInt8Array(out byte[] value); + void GetInt16Array(out short[] value); + void GetUInt16Array(out ushort[] value); + void GetInt32Array(out int[] value); + void GetUInt32Array(out uint[] value); + void GetInt64Array(out long[] value); + void GetUInt64Array(out ulong[] value); + void GetSingleArray(out float[] value); + void GetDoubleArray(out double[] value); + void GetChar16Array(out char[] value); + void GetBooleanArray(out bool[] value); + void GetStringArray(out string[] value); + void GetInspectableArray(out object[] value); + void GetGuidArray(out Guid[] value); + void GetDateTimeArray(out global::System.DateTimeOffset[] value); + void GetTimeSpanArray(out global::System.TimeSpan[] value); + void GetPointArray(out Point[] value); + void GetSizeArray(out Size[] value); + void GetRectArray(out Rect[] value); + bool IsNumericScalar { get; } + PropertyType Type { get; } + } +} + +namespace ABI.Windows.Foundation +{ + internal static class ManagedIPropertyValueImpl + { + private const int TYPE_E_TYPEMISMATCH = unchecked((int)0x80028CA0); + private const int DISP_E_OVERFLOW = unchecked((int)0x8002000A); + private static IPropertyValue.Vftbl AbiToProjectionVftable; + public static IntPtr AbiToProjectionVftablePtr; + + + static unsafe ManagedIPropertyValueImpl() + { + AbiToProjectionVftable = new IPropertyValue.Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + _get_Type_0 = (delegate*)&Do_Abi_get_Type_0, + _get_IsNumericScalar_1 = (delegate*)&Do_Abi_get_IsNumericScalar_1, + _GetUInt8_2 = (delegate*)&Do_Abi_GetUInt8_2, + _GetInt16_3 = (delegate*)&Do_Abi_GetInt16_3, + _GetUInt16_4 = (delegate*)&Do_Abi_GetUInt16_4, + _GetInt32_5 = (delegate*)&Do_Abi_GetInt32_5, + _GetUInt32_6 = (delegate*)&Do_Abi_GetUInt32_6, + _GetInt64_7 = (delegate*)&Do_Abi_GetInt64_7, + _GetUInt64_8 = (delegate*)&Do_Abi_GetUInt64_8, + _GetSingle_9 = (delegate*)&Do_Abi_GetSingle_9, + _GetDouble_10 = (delegate*)&Do_Abi_GetDouble_10, + _GetChar16_11 = (delegate*)&Do_Abi_GetChar16_11, + _GetBoolean_12 = (delegate*)&Do_Abi_GetBoolean_12, + _GetString_13 = (delegate*)&Do_Abi_GetString_13, + _GetGuid_14 = (delegate*)&Do_Abi_GetGuid_14, + _GetDateTime_15 = (delegate*)&Do_Abi_GetDateTime_15, + _GetTimeSpan_16 = (delegate*)&Do_Abi_GetTimeSpan_16, + _GetPoint_17 = (delegate*)&Do_Abi_GetPoint_17, + _GetSize_18 = (delegate*)&Do_Abi_GetSize_18, + _GetRect_19 = (delegate*)&Do_Abi_GetRect_19, + _GetUInt8Array_20 = (delegate*)&Do_Abi_GetUInt8Array_20, + _GetInt16Array_21 = (delegate*)&Do_Abi_GetInt16Array_21, + _GetUInt16Array_22 = (delegate*)&Do_Abi_GetUInt16Array_22, + _GetInt32Array_23 = (delegate*)&Do_Abi_GetInt32Array_23, + _GetUInt32Array_24 = (delegate*)&Do_Abi_GetUInt32Array_24, + _GetInt64Array_25 = (delegate*)&Do_Abi_GetInt64Array_25, + _GetUInt64Array_26 = (delegate*)&Do_Abi_GetUInt64Array_26, + _GetSingleArray_27 = (delegate*)&Do_Abi_GetSingleArray_27, + _GetDoubleArray_28 = (delegate*)&Do_Abi_GetDoubleArray_28, + _GetChar16Array_29 = (delegate*)&Do_Abi_GetChar16Array_29, + _GetBooleanArray_30 = (delegate*)&Do_Abi_GetBooleanArray_30, + _GetStringArray_31 = (delegate*)&Do_Abi_GetStringArray_31, + _GetInspectableArray_32 = (delegate*)&Do_Abi_GetInspectableArray_32, + _GetGuidArray_33 = (delegate*)&Do_Abi_GetGuidArray_33, + _GetDateTimeArray_34 = (delegate*)&Do_Abi_GetDateTimeArray_34, + _GetTimeSpanArray_35 = (delegate*)&Do_Abi_GetTimeSpanArray_35, + _GetPointArray_36 = (delegate*)&Do_Abi_GetPointArray_36, + _GetSizeArray_37 = (delegate*)&Do_Abi_GetSizeArray_37, + _GetRectArray_38 = (delegate*)&Do_Abi_GetRectArray_38, + + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(ManagedIPropertyValueImpl), Marshal.SizeOf() + sizeof(IntPtr) * 39); + Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static volatile Dictionary s_numericScalarTypes; + + private static Dictionary NumericScalarTypes + { + get + { + if (s_numericScalarTypes == null) + { + var numericScalarTypes = new Dictionary { + { typeof(byte), global::Windows.Foundation.PropertyType.UInt8 }, + { typeof(short), global::Windows.Foundation.PropertyType.Int16 }, + { typeof(ushort), global::Windows.Foundation.PropertyType.UInt16 }, + { typeof(int), global::Windows.Foundation.PropertyType.Int32 }, + { typeof(uint), global::Windows.Foundation.PropertyType.UInt32 }, + { typeof(long), global::Windows.Foundation.PropertyType.Int64 }, + { typeof(ulong), global::Windows.Foundation.PropertyType.UInt64 }, + { typeof(float), global::Windows.Foundation.PropertyType.Single }, + { typeof(double), global::Windows.Foundation.PropertyType.Double } + }; + + s_numericScalarTypes = numericScalarTypes; + } + + return s_numericScalarTypes; + } + } + + /// + /// Unbox a value of a projected Windows.Foundation struct type + /// to a structurally equivalent type with the same name. + /// + /// The target type. + /// The object to unbox. + /// The unboxed value. + private static T UnboxValue(object value) + where T : struct + { + Type valueType = value.GetType(); + + if (valueType.FullName == typeof(T).FullName && Marshal.SizeOf(valueType) == Marshal.SizeOf()) + { + return Unsafe.As>(value).Value; + } + + throw new InvalidCastException("", TYPE_E_TYPEMISMATCH); + } + +#pragma warning disable CS0649 + private class Boxed + where T : struct + { + public T Value; + } +#pragma warning restore CS0649 + + private static T[] UnboxArray(object value) + where T : struct + { + if (!(value is Array dataArray)) + { + throw new InvalidCastException(); + } + + // If we do not have the correct array type, then we need to convert the array element-by-element + // to a new array of the requested type + T[] coercedArray = new T[dataArray.Length]; + for (int i = 0; i < dataArray.Length; ++i) + { + try + { + coercedArray[i] = UnboxValue(dataArray.GetValue(i)); + } + catch (InvalidCastException elementCastException) + { + //global::System.Exception e = new InvalidCastException(string.Format(SR.InvalidCast_WinRTIPropertyValueArrayCoersion, value.GetType(), typeof(T[]).Name, i, elementCastException.Message), elementCastException.HResult); + global::System.Exception e = new InvalidCastException("", elementCastException.HResult); + throw e; + } + } + return coercedArray; + } + + private static bool IsCoercable(object value) + { + // String <--> Guid is allowed + // Converting from an object to a string, Guid, or numeric scalar is allowed. + if (value.GetType() == typeof(string) || value.GetType() == typeof(Guid) || value.GetType() != typeof(object)) + { + return true; + } + + // All numeric scalars can also be coerced + return NumericScalarTypes.TryGetValue(value.GetType(), out _); + } + + /// + /// Coerce the managd object to an object of type . + /// + /// The target type. + /// The value. + /// The coerced value. + private static T CoerceValue(object value) + { + if (value is T u) + { + return u; + } + + if (value is global::Windows.Foundation.IPropertyValue ipv) + { + if (typeof(T) == typeof(byte)) + { + return (T)(object)ipv.GetUInt8(); + } + if (typeof(T) == typeof(short)) + { + return (T)(object)ipv.GetInt16(); + } + if (typeof(T) == typeof(ushort)) + { + return (T)(object)ipv.GetUInt16(); + } + if (typeof(T) == typeof(int)) + { + return (T)(object)ipv.GetInt32(); + } + if (typeof(T) == typeof(uint)) + { + return (T)(object)ipv.GetUInt32(); + } + if (typeof(T) == typeof(long)) + { + return (T)(object)ipv.GetInt64(); + } + if (typeof(T) == typeof(ulong)) + { + return (T)(object)ipv.GetUInt64(); + } + if (typeof(T) == typeof(float)) + { + return (T)(object)ipv.GetSingle(); + } + if (typeof(T) == typeof(double)) + { + return (T)(object)ipv.GetDouble(); + } + } + + if (!IsCoercable(value)) + { + throw new InvalidCastException(); + } + + try + { + if (value is string str && typeof(T) == typeof(Guid)) + { + return (T)(object)Guid.Parse(str); + } + else if (value is Guid guid && typeof(T) == typeof(string)) + { + return (T)(object)guid.ToString("D", global::System.Globalization.CultureInfo.InvariantCulture); + } + else + { + if (NumericScalarTypes.TryGetValue(typeof(T), out _)) + { + return (T)Convert.ChangeType(value, typeof(T), global::System.Globalization.CultureInfo.InvariantCulture); + } + } + } + catch (FormatException) + { + // throw new InvalidCastException(string.Format(SR.InvalidCast_WinRTIPropertyValueElement, value.GetType(), typeof(T).Name), TYPE_E_TYPEMISMATCH); + throw new InvalidCastException("", TYPE_E_TYPEMISMATCH); + } + catch (InvalidCastException) + { + // throw new InvalidCastException(string.Format(SR.InvalidCast_WinRTIPropertyValueElement, value.GetType(), typeof(T).Name), TYPE_E_TYPEMISMATCH); + throw new InvalidCastException("", TYPE_E_TYPEMISMATCH); + } + catch (OverflowException) + { + // throw new InvalidCastException(string.Format(SR.InvalidCast_WinRTIPropertyValueCoersion, value.GetType(), value, typeof(T).Name), DISP_E_OVERFLOW); + throw new InvalidCastException("", DISP_E_OVERFLOW); + } + + throw new InvalidCastException(); + } + + private static T[] CoerceArray(object value) + { + if (value is T[] arr) + { + return arr; + } + + if (!(value is Array dataArray)) + { + throw new InvalidCastException(); + } + + // If we do not have the correct array type, then we need to convert the array element-by-element + // to a new array of the requested type + T[] coercedArray = new T[dataArray.Length]; + for (int i = 0; i < dataArray.Length; ++i) + { + try + { + coercedArray[i] = CoerceValue(dataArray.GetValue(i)); + } + catch (InvalidCastException elementCastException) + { + //global::System.Exception e = new InvalidCastException(string.Format(SR.InvalidCast_WinRTIPropertyValueArrayCoersion, value.GetType(), typeof(T[]).Name, i, elementCastException.Message), elementCastException.HResult); + global::System.Exception e = new InvalidCastException("", elementCastException.HResult); + throw e; + } + } + return coercedArray; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetUInt8_2(IntPtr thisPtr, byte* value) + { + try + { + *value = CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetInt16_3(IntPtr thisPtr, short* value) + { + try + { + *value = CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetUInt16_4(IntPtr thisPtr, ushort* value) + { + try + { + *value = CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetInt32_5(IntPtr thisPtr, int* value) + { + try + { + *value = CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetUInt32_6(IntPtr thisPtr, uint* value) + { + try + { + *value = CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetInt64_7(IntPtr thisPtr, long* value) + { + try + { + *value = CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetUInt64_8(IntPtr thisPtr, ulong* value) + { + try + { + *value = CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetSingle_9(IntPtr thisPtr, float* value) + { + try + { + *value = CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetDouble_10(IntPtr thisPtr, double* value) + { + try + { + *value = CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetChar16_11(IntPtr thisPtr, ushort* value) + { + + try + { + *value = (ushort)CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetBoolean_12(IntPtr thisPtr, byte* value) + { + + try + { + *value = (byte)(CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)) ? 1 : 0); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetString_13(IntPtr thisPtr, IntPtr* value) + { + + try + { + *value = MarshalString.FromManaged(CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr))); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetGuid_14(IntPtr thisPtr, Guid* value) + { + + try + { + *value = CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetDateTime_15(IntPtr thisPtr, global::ABI.System.DateTimeOffset* value) + { + + try + { + *value = ABI.System.DateTimeOffset.FromManaged(CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr))); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetTimeSpan_16(IntPtr thisPtr, global::ABI.System.TimeSpan* value) + { + + try + { + *value = ABI.System.TimeSpan.FromManaged(CoerceValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr))); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetPoint_17(IntPtr thisPtr, global::Windows.Foundation.Point* value) + { + + try + { + *value = UnboxValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetSize_18(IntPtr thisPtr, global::Windows.Foundation.Size* value) + { + + try + { + *value = UnboxValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetRect_19(IntPtr thisPtr, global::Windows.Foundation.Rect* value) + { + + try + { + *value = UnboxValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetUInt8Array_20(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + byte[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetInt16Array_21(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + short[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetUInt16Array_22(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + ushort[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetInt32Array_23(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + int[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetUInt32Array_24(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + uint[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetInt64Array_25(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + long[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetUInt64Array_26(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + ulong[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetSingleArray_27(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + float[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetDoubleArray_28(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + double[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetChar16Array_29(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + char[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalNonBlittable.FromManagedArray(__value); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetBooleanArray_30(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + bool[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalNonBlittable.FromManagedArray(__value); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetStringArray_31(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + string[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalString.FromManagedArray(__value); + + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetInspectableArray_32(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + object[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalInspectable.FromManagedArray(__value); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetGuidArray_33(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + Guid[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetDateTimeArray_34(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + global::System.DateTimeOffset[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalNonBlittable.FromManagedArray(__value); + + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetTimeSpanArray_35(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + global::System.TimeSpan[] __value = default; + + try + { + __value = CoerceArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalNonBlittable.FromManagedArray(__value); + + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetPointArray_36(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + global::Windows.Foundation.Point[] __value = default; + + try + { + __value = UnboxArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetSizeArray_37(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + global::Windows.Foundation.Size[] __value = default; + + try + { + __value = UnboxArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_GetRectArray_38(IntPtr thisPtr, int* __valueSize, IntPtr* value) + { + + + + global::Windows.Foundation.Rect[] __value = default; + + try + { + __value = UnboxArray(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + (*__valueSize, *value) = MarshalBlittable.FromManagedArray(__value); + + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_get_IsNumericScalar_1(IntPtr thisPtr, byte* value) + { + + try + { + *value = (byte)(NumericScalarTypes.TryGetValue(global::WinRT.ComWrappersSupport.FindObject(thisPtr).GetType(), out _) ? 1 : 0); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_get_Type_0(IntPtr thisPtr, global::Windows.Foundation.PropertyType* value) + { + + try + { + *value = GetPropertyTypeOfObject(global::WinRT.ComWrappersSupport.FindObject(thisPtr)); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + + private static unsafe global::Windows.Foundation.PropertyType GetPropertyTypeOfObject(object obj) + { + global::Windows.Foundation.PropertyType value; + global::System.Type managedType = obj.GetType(); + bool isArray = managedType.IsArray; + if (isArray) + { + managedType = managedType.GetElementType(); + } + if (!NumericScalarTypes.TryGetValue(managedType, out value)) + { + if (managedType == typeof(string)) + { + value = global::Windows.Foundation.PropertyType.String; + } + else if (managedType == typeof(char)) + { + value = global::Windows.Foundation.PropertyType.Char16; + } + else if (managedType == typeof(bool)) + { + value = global::Windows.Foundation.PropertyType.Boolean; + } + else if (managedType == typeof(global::System.DateTimeOffset)) + { + value = global::Windows.Foundation.PropertyType.DateTime; + } + else if (managedType == typeof(global::System.TimeSpan)) + { + value = global::Windows.Foundation.PropertyType.TimeSpan; + } + else if (managedType == typeof(global::System.Guid)) + { + value = global::Windows.Foundation.PropertyType.Guid; + } + else if (managedType.FullName == "Windows.Foundation.Point") + { + value = global::Windows.Foundation.PropertyType.Point; + } + else if (managedType.FullName == "Windows.Foundation.Rect") + { + value = global::Windows.Foundation.PropertyType.Rect; + } + else if (managedType.FullName == "Windows.Foundation.Size") + { + value = global::Windows.Foundation.PropertyType.Size; + } + else if (managedType == typeof(object)) + { + value = global::Windows.Foundation.PropertyType.Inspectable; + } + else if (typeof(Delegate).IsAssignableFrom(managedType)) + { + value = global::Windows.Foundation.PropertyType.OtherType; + } + else if (!managedType.IsValueType && managedType != typeof(Type) && isArray) + { + // Treat arrays of interfaces as though they are arrays of object. + value = global::Windows.Foundation.PropertyType.Inspectable; + } + else + { + value = global::Windows.Foundation.PropertyType.OtherType; + } + } + if (isArray) + { + // The array values for Windows.Foundation.PropertyType are all 1024 above their scalar equivalents + value = (global::Windows.Foundation.PropertyType)((int)value + 1024); + } + + return value; + } + } + + + + [DynamicInterfaceCastableImplementation] + [Guid("4BD682DD-7554-40E9-9A9B-82654EDE7E62")] + internal unsafe interface IPropertyValue : global::Windows.Foundation.IPropertyValue + { + [Guid("4BD682DD-7554-40E9-9A9B-82654EDE7E62")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + internal void* _get_Type_0; + public delegate* stdcall get_Type_0 { get => (delegate* stdcall)_get_Type_0; set => _get_Type_0 = value; } + public void* _get_IsNumericScalar_1; + public delegate* stdcall get_IsNumericScalar_1 { get => (delegate* stdcall)_get_IsNumericScalar_1; set => _get_IsNumericScalar_1 = value; } + internal void* _GetUInt8_2; + public delegate* stdcall GetUInt8_2 { get => (delegate* stdcall)_GetUInt8_2; set => _GetUInt8_2 = value; } + internal void* _GetInt16_3; + public delegate* stdcall GetInt16_3 { get => (delegate* stdcall)_GetInt16_3; set => _GetInt16_3 = value; } + internal void* _GetUInt16_4; + public delegate* stdcall GetUInt16_4 { get => (delegate* stdcall)_GetUInt16_4; set => _GetUInt16_4 = value; } + internal void* _GetInt32_5; + public delegate* stdcall GetInt32_5 { get => (delegate* stdcall)_GetInt32_5; set => _GetInt32_5 = value; } + internal void* _GetUInt32_6; + public delegate* stdcall GetUInt32_6 { get => (delegate* stdcall)_GetUInt32_6; set => _GetUInt32_6 = value; } + internal void* _GetInt64_7; + public delegate* stdcall GetInt64_7 { get => (delegate* stdcall)_GetInt64_7; set => _GetInt64_7 = value; } + internal void* _GetUInt64_8; + public delegate* stdcall GetUInt64_8 { get => (delegate* stdcall)_GetUInt64_8; set => _GetUInt64_8 = value; } + internal void* _GetSingle_9; + public delegate* stdcall GetSingle_9 { get => (delegate* stdcall)_GetSingle_9; set => _GetSingle_9 = value; } + internal void* _GetDouble_10; + public delegate* stdcall GetDouble_10 { get => (delegate* stdcall)_GetDouble_10; set => _GetDouble_10 = value; } + internal void* _GetChar16_11; + public delegate* stdcall GetChar16_11 { get => (delegate* stdcall)_GetChar16_11; set => _GetChar16_11 = value; } + internal void* _GetBoolean_12; + public delegate* stdcall GetBoolean_12 { get => (delegate* stdcall)_GetBoolean_12; set => _GetBoolean_12 = value; } + internal void* _GetString_13; + public delegate* stdcall GetString_13 { get => (delegate* stdcall)_GetString_13; set => _GetString_13 = value; } + internal void* _GetGuid_14; + public delegate* stdcall GetGuid_14 { get => (delegate* stdcall)_GetGuid_14; set => _GetGuid_14 = value; } + internal void* _GetDateTime_15; + public delegate* stdcall GetDateTime_15 { get => (delegate* stdcall)_GetDateTime_15; set => _GetDateTime_15 = value; } + internal void* _GetTimeSpan_16; + public delegate* stdcall GetTimeSpan_16 { get => (delegate* stdcall)_GetTimeSpan_16; set => _GetTimeSpan_16 = value; } + internal void* _GetPoint_17; + public delegate* stdcall GetPoint_17 { get => (delegate* stdcall)_GetPoint_17; set => _GetPoint_17 = value; } + internal void* _GetSize_18; + public delegate* stdcall GetSize_18 { get => (delegate* stdcall)_GetSize_18; set => _GetSize_18 = value; } + internal void* _GetRect_19; + public delegate* stdcall GetRect_19 { get => (delegate* stdcall)_GetRect_19; set => _GetRect_19 = value; } + internal void* _GetUInt8Array_20; + public delegate* stdcall GetUInt8Array_20 { get => (delegate* stdcall)_GetUInt8Array_20; set => _GetUInt8Array_20 = value; } + internal void* _GetInt16Array_21; + public delegate* stdcall GetInt16Array_21 { get => (delegate* stdcall)_GetInt16Array_21; set => _GetInt16Array_21 = value; } + internal void* _GetUInt16Array_22; + public delegate* stdcall GetUInt16Array_22 { get => (delegate* stdcall)_GetUInt16Array_22; set => _GetUInt16Array_22 = value; } + internal void* _GetInt32Array_23; + public delegate* stdcall GetInt32Array_23 { get => (delegate* stdcall)_GetInt32Array_23; set => _GetInt32Array_23 = value; } + internal void* _GetUInt32Array_24; + public delegate* stdcall GetUInt32Array_24 { get => (delegate* stdcall)_GetUInt32Array_24; set => _GetUInt32Array_24 = value; } + internal void* _GetInt64Array_25; + public delegate* stdcall GetInt64Array_25 { get => (delegate* stdcall)_GetInt64Array_25; set => _GetInt64Array_25 = value; } + internal void* _GetUInt64Array_26; + public delegate* stdcall GetUInt64Array_26 { get => (delegate* stdcall)_GetUInt64Array_26; set => _GetUInt64Array_26 = value; } + internal void* _GetSingleArray_27; + public delegate* stdcall GetSingleArray_27 { get => (delegate* stdcall)_GetSingleArray_27; set => _GetSingleArray_27 = value; } + internal void* _GetDoubleArray_28; + public delegate* stdcall GetDoubleArray_28 { get => (delegate* stdcall)_GetDoubleArray_28; set => _GetDoubleArray_28 = value; } + internal void* _GetChar16Array_29; + public delegate* stdcall GetChar16Array_29 { get => (delegate* stdcall)_GetChar16Array_29; set => _GetChar16Array_29 = value; } + internal void* _GetBooleanArray_30; + public delegate* stdcall GetBooleanArray_30 { get => (delegate* stdcall)_GetBooleanArray_30; set => _GetBooleanArray_30 = value; } + internal void* _GetStringArray_31; + public delegate* stdcall GetStringArray_31 { get => (delegate* stdcall)_GetStringArray_31; set => _GetStringArray_31 = value; } + internal void* _GetInspectableArray_32; + public delegate* stdcall GetInspectableArray_32 { get => (delegate* stdcall)_GetInspectableArray_32; set => _GetInspectableArray_32 = value; } + internal void* _GetGuidArray_33; + public delegate* stdcall GetGuidArray_33 { get => (delegate* stdcall)_GetGuidArray_33; set => _GetGuidArray_33 = value; } + internal void* _GetDateTimeArray_34; + public delegate* stdcall GetDateTimeArray_34 { get => (delegate* stdcall)_GetDateTimeArray_34; set => _GetDateTimeArray_34 = value; } + internal void* _GetTimeSpanArray_35; + public delegate* stdcall GetTimeSpanArray_35 { get => (delegate* stdcall)_GetTimeSpanArray_35; set => _GetTimeSpanArray_35 = value; } + internal void* _GetPointArray_36; + public delegate* stdcall GetPointArray_36 { get => (delegate* stdcall)_GetPointArray_36; set => _GetPointArray_36 = value; } + internal void* _GetSizeArray_37; + public delegate* stdcall GetSizeArray_37 { get => (delegate* stdcall)_GetSizeArray_37; set => _GetSizeArray_37 = value; } + internal void* _GetRectArray_38; + public delegate* stdcall GetRectArray_38 { get => (delegate* stdcall)_GetRectArray_38; set => _GetRectArray_38 = value; } + } + + unsafe byte global::Windows.Foundation.IPropertyValue.GetUInt8() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + byte __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetUInt8_2(ThisPtr, out __retval)); + return __retval; + } + + unsafe short global::Windows.Foundation.IPropertyValue.GetInt16() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + short __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetInt16_3(ThisPtr, out __retval)); + return __retval; + } + + unsafe ushort global::Windows.Foundation.IPropertyValue.GetUInt16() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + ushort __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetUInt16_4(ThisPtr, out __retval)); + return __retval; + } + + unsafe int global::Windows.Foundation.IPropertyValue.GetInt32() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetInt32_5(ThisPtr, out __retval)); + return __retval; + } + + unsafe uint global::Windows.Foundation.IPropertyValue.GetUInt32() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + uint __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetUInt32_6(ThisPtr, out __retval)); + return __retval; + } + + unsafe long global::Windows.Foundation.IPropertyValue.GetInt64() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + long __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetInt64_7(ThisPtr, out __retval)); + return __retval; + } + + unsafe ulong global::Windows.Foundation.IPropertyValue.GetUInt64() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + ulong __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetUInt64_8(ThisPtr, out __retval)); + return __retval; + } + + unsafe float global::Windows.Foundation.IPropertyValue.GetSingle() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + float __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetSingle_9(ThisPtr, out __retval)); + return __retval; + } + + unsafe double global::Windows.Foundation.IPropertyValue.GetDouble() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + double __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetDouble_10(ThisPtr, out __retval)); + return __retval; + } + + unsafe char global::Windows.Foundation.IPropertyValue.GetChar16() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + ushort __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetChar16_11(ThisPtr, out __retval)); + return (char)__retval; + } + + unsafe bool global::Windows.Foundation.IPropertyValue.GetBoolean() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + byte __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetBoolean_12(ThisPtr, out __retval)); + return __retval != 0; + } + + unsafe string global::Windows.Foundation.IPropertyValue.GetString() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetString_13(ThisPtr, out __retval)); + return MarshalString.FromAbi(__retval); + } + finally + { + MarshalString.DisposeAbi(__retval); + } + } + + unsafe Guid global::Windows.Foundation.IPropertyValue.GetGuid() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + Guid __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetGuid_14(ThisPtr, out __retval)); + return __retval; + } + + unsafe global::System.DateTimeOffset global::Windows.Foundation.IPropertyValue.GetDateTime() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::ABI.System.DateTimeOffset __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetDateTime_15(ThisPtr, out __retval)); + return global::ABI.System.DateTimeOffset.FromAbi(__retval); + } + finally + { + global::ABI.System.DateTimeOffset.DisposeAbi(__retval); + } + } + + unsafe global::System.TimeSpan global::Windows.Foundation.IPropertyValue.GetTimeSpan() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::ABI.System.TimeSpan __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetTimeSpan_16(ThisPtr, out __retval)); + return global::ABI.System.TimeSpan.FromAbi(__retval); + } + finally + { + global::ABI.System.TimeSpan.DisposeAbi(__retval); + } + } + + unsafe global::Windows.Foundation.Point global::Windows.Foundation.IPropertyValue.GetPoint() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::Windows.Foundation.Point __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetPoint_17(ThisPtr, out __retval)); + return __retval; + } + + unsafe global::Windows.Foundation.Size global::Windows.Foundation.IPropertyValue.GetSize() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::Windows.Foundation.Size __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetSize_18(ThisPtr, out __retval)); + return __retval; + } + + unsafe global::Windows.Foundation.Rect global::Windows.Foundation.IPropertyValue.GetRect() + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::Windows.Foundation.Rect __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetRect_19(ThisPtr, out __retval)); + return __retval; + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetUInt8Array(out byte[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetUInt8Array_20(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetInt16Array(out short[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetInt16Array_21(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetUInt16Array(out ushort[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetUInt16Array_22(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetInt32Array(out int[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetInt32Array_23(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetUInt32Array(out uint[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetUInt32Array_24(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetInt64Array(out long[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetInt64Array_25(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetUInt64Array(out ulong[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetUInt64Array_26(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetSingleArray(out float[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetSingleArray_27(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetDoubleArray(out double[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetDoubleArray_28(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetChar16Array(out char[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetChar16Array_29(ThisPtr, out __value_length, out __value_data)); + value = MarshalNonBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalNonBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetBooleanArray(out bool[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetBooleanArray_30(ThisPtr, out __value_length, out __value_data)); + value = MarshalNonBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalNonBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetStringArray(out string[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetStringArray_31(ThisPtr, out __value_length, out __value_data)); + value = MarshalString.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalString.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetInspectableArray(out object[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetInspectableArray_32(ThisPtr, out __value_length, out __value_data)); + value = MarshalInspectable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalInspectable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetGuidArray(out Guid[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetGuidArray_33(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetDateTimeArray(out global::System.DateTimeOffset[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetDateTimeArray_34(ThisPtr, out __value_length, out __value_data)); + value = MarshalNonBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalNonBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetTimeSpanArray(out global::System.TimeSpan[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetTimeSpanArray_35(ThisPtr, out __value_length, out __value_data)); + value = MarshalNonBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalNonBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetPointArray(out global::Windows.Foundation.Point[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetPointArray_36(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetSizeArray(out global::Windows.Foundation.Size[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetSizeArray_37(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe void global::Windows.Foundation.IPropertyValue.GetRectArray(out global::Windows.Foundation.Rect[] value) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + int __value_length = default; + IntPtr __value_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetRectArray_38(ThisPtr, out __value_length, out __value_data)); + value = MarshalBlittable.FromAbiArray((__value_length, __value_data)); + } + finally + { + MarshalBlittable.DisposeAbiArray((__value_length, __value_data)); + } + } + + unsafe bool global::Windows.Foundation.IPropertyValue.IsNumericScalar + { + get + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + byte __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_IsNumericScalar_1(ThisPtr, out __retval)); + return __retval != 0; + } + } + + unsafe global::Windows.Foundation.PropertyType global::Windows.Foundation.IPropertyValue.Type + { + get + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::Windows.Foundation.IPropertyValue).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + global::Windows.Foundation.PropertyType __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Type_0(ThisPtr, out __retval)); + return __retval; + } + } + } + + internal static class IPropertyValue_Delegates + { + public unsafe delegate int get_Type_0(IntPtr thisPtr, global::Windows.Foundation.PropertyType* value); + public unsafe delegate int get_IsNumericScalar_1(IntPtr thisPtr, byte* value); + public unsafe delegate int GetUInt8_2(IntPtr thisPtr, byte* value); + public unsafe delegate int GetInt16_3(IntPtr thisPtr, short* value); + public unsafe delegate int GetUInt16_4(IntPtr thisPtr, ushort* value); + public unsafe delegate int GetInt32_5(IntPtr thisPtr, int* value); + public unsafe delegate int GetUInt32_6(IntPtr thisPtr, uint* value); + public unsafe delegate int GetInt64_7(IntPtr thisPtr, long* value); + public unsafe delegate int GetUInt64_8(IntPtr thisPtr, ulong* value); + public unsafe delegate int GetSingle_9(IntPtr thisPtr, float* value); + public unsafe delegate int GetDouble_10(IntPtr thisPtr, double* value); + public unsafe delegate int GetChar16_11(IntPtr thisPtr, ushort* value); + public unsafe delegate int GetBoolean_12(IntPtr thisPtr, byte* value); + public unsafe delegate int GetString_13(IntPtr thisPtr, IntPtr* value); + public unsafe delegate int GetGuid_14(IntPtr thisPtr, Guid* value); + public unsafe delegate int GetDateTime_15(IntPtr thisPtr, global::ABI.System.DateTimeOffset* value); + public unsafe delegate int GetTimeSpan_16(IntPtr thisPtr, global::ABI.System.TimeSpan* value); + public unsafe delegate int GetPoint_17(IntPtr thisPtr, global::Windows.Foundation.Point* value); + public unsafe delegate int GetSize_18(IntPtr thisPtr, global::Windows.Foundation.Size* value); + public unsafe delegate int GetRect_19(IntPtr thisPtr, global::Windows.Foundation.Rect* value); + public unsafe delegate int GetUInt8Array_20(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetInt16Array_21(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetUInt16Array_22(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetInt32Array_23(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetUInt32Array_24(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetInt64Array_25(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetUInt64Array_26(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetSingleArray_27(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetDoubleArray_28(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetChar16Array_29(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetBooleanArray_30(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetStringArray_31(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetInspectableArray_32(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetGuidArray_33(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetDateTimeArray_34(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetTimeSpanArray_35(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetPointArray_36(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetSizeArray_37(IntPtr thisPtr, int* __valueSize, IntPtr* value); + public unsafe delegate int GetRectArray_38(IntPtr thisPtr, int* __valueSize, IntPtr* value); + } +} diff --git a/WinRT.Runtime/Projections/IPropertyValue.cs b/WinRT.Runtime/Projections/IPropertyValue.netstandard2.0.cs similarity index 92% rename from WinRT.Runtime/Projections/IPropertyValue.cs rename to WinRT.Runtime/Projections/IPropertyValue.netstandard2.0.cs index 529464858..cb7c9b26f 100644 --- a/WinRT.Runtime/Projections/IPropertyValue.cs +++ b/WinRT.Runtime/Projections/IPropertyValue.netstandard2.0.cs @@ -6,7 +6,7 @@ using WinRT.Interop; namespace Windows.Foundation -{ +{ internal enum PropertyType : uint { Empty = 0, @@ -104,97 +104,57 @@ internal static class ManagedIPropertyValueImpl private const int TYPE_E_TYPEMISMATCH = unchecked((int)0x80028CA0); private const int DISP_E_OVERFLOW = unchecked((int)0x8002000A); private static IPropertyValue.Vftbl AbiToProjectionVftable; - public static IntPtr AbiToProjectionVftablePtr; - -#if NETSTANDARD2_0 - private static readonly Delegate[] DelegateCache = new Delegate[39]; -#endif + public static IntPtr AbiToProjectionVftablePtr; + + + private static readonly Delegate[] DelegateCache = new Delegate[39]; + static unsafe ManagedIPropertyValueImpl() { AbiToProjectionVftable = new IPropertyValue.Vftbl { - IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 - _get_Type_0 = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new IPropertyValue_Delegates.get_Type_0(Do_Abi_get_Type_0)).ToPointer(), - _get_IsNumericScalar_1 = Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new IPropertyValue_Delegates.get_IsNumericScalar_1(Do_Abi_get_IsNumericScalar_1)).ToPointer(), - _GetUInt8_2 = Marshal.GetFunctionPointerForDelegate(DelegateCache[2] = new IPropertyValue_Delegates.GetUInt8_2(Do_Abi_GetUInt8_2)).ToPointer(), - _GetInt16_3 = Marshal.GetFunctionPointerForDelegate(DelegateCache[3] = new IPropertyValue_Delegates.GetInt16_3(Do_Abi_GetInt16_3)).ToPointer(), - _GetUInt16_4 = Marshal.GetFunctionPointerForDelegate(DelegateCache[4] = new IPropertyValue_Delegates.GetUInt16_4(Do_Abi_GetUInt16_4)).ToPointer(), - _GetInt32_5 = Marshal.GetFunctionPointerForDelegate(DelegateCache[5] = new IPropertyValue_Delegates.GetInt32_5(Do_Abi_GetInt32_5)).ToPointer(), - _GetUInt32_6 = Marshal.GetFunctionPointerForDelegate(DelegateCache[6] = new IPropertyValue_Delegates.GetUInt32_6(Do_Abi_GetUInt32_6)).ToPointer(), - _GetInt64_7 = Marshal.GetFunctionPointerForDelegate(DelegateCache[7] = new IPropertyValue_Delegates.GetInt64_7(Do_Abi_GetInt64_7)).ToPointer(), - _GetUInt64_8 = Marshal.GetFunctionPointerForDelegate(DelegateCache[8] = new IPropertyValue_Delegates.GetUInt64_8(Do_Abi_GetUInt64_8)).ToPointer(), - _GetSingle_9 = Marshal.GetFunctionPointerForDelegate(DelegateCache[9] = new IPropertyValue_Delegates.GetSingle_9(Do_Abi_GetSingle_9)).ToPointer(), - _GetDouble_10 = Marshal.GetFunctionPointerForDelegate(DelegateCache[10] = new IPropertyValue_Delegates.GetDouble_10(Do_Abi_GetDouble_10)).ToPointer(), - _GetChar16_11 = Marshal.GetFunctionPointerForDelegate(DelegateCache[11] = new IPropertyValue_Delegates.GetChar16_11(Do_Abi_GetChar16_11)).ToPointer(), - _GetBoolean_12 = Marshal.GetFunctionPointerForDelegate(DelegateCache[12] = new IPropertyValue_Delegates.GetBoolean_12(Do_Abi_GetBoolean_12)).ToPointer(), - _GetString_13 = Marshal.GetFunctionPointerForDelegate(DelegateCache[13] = new IPropertyValue_Delegates.GetString_13(Do_Abi_GetString_13)).ToPointer(), - _GetGuid_14 = Marshal.GetFunctionPointerForDelegate(DelegateCache[14] = new IPropertyValue_Delegates.GetGuid_14(Do_Abi_GetGuid_14)).ToPointer(), - _GetDateTime_15 = Marshal.GetFunctionPointerForDelegate(DelegateCache[15] = new IPropertyValue_Delegates.GetDateTime_15(Do_Abi_GetDateTime_15)).ToPointer(), - _GetTimeSpan_16 = Marshal.GetFunctionPointerForDelegate(DelegateCache[16] = new IPropertyValue_Delegates.GetTimeSpan_16(Do_Abi_GetTimeSpan_16)).ToPointer(), - _GetPoint_17 = Marshal.GetFunctionPointerForDelegate(DelegateCache[17] = new IPropertyValue_Delegates.GetPoint_17(Do_Abi_GetPoint_17)).ToPointer(), - _GetSize_18 = Marshal.GetFunctionPointerForDelegate(DelegateCache[18] = new IPropertyValue_Delegates.GetSize_18(Do_Abi_GetSize_18)).ToPointer(), - _GetRect_19 = Marshal.GetFunctionPointerForDelegate(DelegateCache[19] = new IPropertyValue_Delegates.GetRect_19(Do_Abi_GetRect_19)).ToPointer(), - _GetUInt8Array_20 = Marshal.GetFunctionPointerForDelegate(DelegateCache[20] = new IPropertyValue_Delegates.GetUInt8Array_20(Do_Abi_GetUInt8Array_20)).ToPointer(), - _GetInt16Array_21 = Marshal.GetFunctionPointerForDelegate(DelegateCache[21] = new IPropertyValue_Delegates.GetInt16Array_21(Do_Abi_GetInt16Array_21)).ToPointer(), - _GetUInt16Array_22 = Marshal.GetFunctionPointerForDelegate(DelegateCache[22] = new IPropertyValue_Delegates.GetUInt16Array_22(Do_Abi_GetUInt16Array_22)).ToPointer(), - _GetInt32Array_23 = Marshal.GetFunctionPointerForDelegate(DelegateCache[23] = new IPropertyValue_Delegates.GetInt32Array_23(Do_Abi_GetInt32Array_23)).ToPointer(), - _GetUInt32Array_24 = Marshal.GetFunctionPointerForDelegate(DelegateCache[24] = new IPropertyValue_Delegates.GetUInt32Array_24(Do_Abi_GetUInt32Array_24)).ToPointer(), - _GetInt64Array_25 = Marshal.GetFunctionPointerForDelegate(DelegateCache[25] = new IPropertyValue_Delegates.GetInt64Array_25(Do_Abi_GetInt64Array_25)).ToPointer(), - _GetUInt64Array_26 = Marshal.GetFunctionPointerForDelegate(DelegateCache[26] = new IPropertyValue_Delegates.GetUInt64Array_26(Do_Abi_GetUInt64Array_26)).ToPointer(), - _GetSingleArray_27 = Marshal.GetFunctionPointerForDelegate(DelegateCache[27] = new IPropertyValue_Delegates.GetSingleArray_27(Do_Abi_GetSingleArray_27)).ToPointer(), - _GetDoubleArray_28 = Marshal.GetFunctionPointerForDelegate(DelegateCache[28] = new IPropertyValue_Delegates.GetDoubleArray_28(Do_Abi_GetDoubleArray_28)).ToPointer(), - _GetChar16Array_29 = Marshal.GetFunctionPointerForDelegate(DelegateCache[29] = new IPropertyValue_Delegates.GetChar16Array_29(Do_Abi_GetChar16Array_29)).ToPointer(), - _GetBooleanArray_30 = Marshal.GetFunctionPointerForDelegate(DelegateCache[30] = new IPropertyValue_Delegates.GetBooleanArray_30(Do_Abi_GetBooleanArray_30)).ToPointer(), - _GetStringArray_31 = Marshal.GetFunctionPointerForDelegate(DelegateCache[31] = new IPropertyValue_Delegates.GetStringArray_31(Do_Abi_GetStringArray_31)).ToPointer(), - _GetInspectableArray_32 = Marshal.GetFunctionPointerForDelegate(DelegateCache[32] = new IPropertyValue_Delegates.GetInspectableArray_32(Do_Abi_GetInspectableArray_32)).ToPointer(), - _GetGuidArray_33 = Marshal.GetFunctionPointerForDelegate(DelegateCache[33] = new IPropertyValue_Delegates.GetGuidArray_33(Do_Abi_GetGuidArray_33)).ToPointer(), - _GetDateTimeArray_34 = Marshal.GetFunctionPointerForDelegate(DelegateCache[34] = new IPropertyValue_Delegates.GetDateTimeArray_34(Do_Abi_GetDateTimeArray_34)).ToPointer(), - _GetTimeSpanArray_35 = Marshal.GetFunctionPointerForDelegate(DelegateCache[35] = new IPropertyValue_Delegates.GetTimeSpanArray_35(Do_Abi_GetTimeSpanArray_35)).ToPointer(), - _GetPointArray_36 = Marshal.GetFunctionPointerForDelegate(DelegateCache[36] = new IPropertyValue_Delegates.GetPointArray_36(Do_Abi_GetPointArray_36)).ToPointer(), - _GetSizeArray_37 = Marshal.GetFunctionPointerForDelegate(DelegateCache[37] = new IPropertyValue_Delegates.GetSizeArray_37(Do_Abi_GetSizeArray_37)).ToPointer(), - _GetRectArray_38 = Marshal.GetFunctionPointerForDelegate(DelegateCache[38] = new IPropertyValue_Delegates.GetRectArray_38(Do_Abi_GetRectArray_38)).ToPointer(), -#else - _get_Type_0 = (delegate*)&Do_Abi_get_Type_0, - _get_IsNumericScalar_1 = (delegate*)&Do_Abi_get_IsNumericScalar_1, - _GetUInt8_2 = (delegate*)&Do_Abi_GetUInt8_2, - _GetInt16_3 = (delegate*)&Do_Abi_GetInt16_3, - _GetUInt16_4 = (delegate*)&Do_Abi_GetUInt16_4, - _GetInt32_5 = (delegate*)&Do_Abi_GetInt32_5, - _GetUInt32_6 = (delegate*)&Do_Abi_GetUInt32_6, - _GetInt64_7 = (delegate*)&Do_Abi_GetInt64_7, - _GetUInt64_8 = (delegate*)&Do_Abi_GetUInt64_8, - _GetSingle_9 = (delegate*)&Do_Abi_GetSingle_9, - _GetDouble_10 = (delegate*)&Do_Abi_GetDouble_10, - _GetChar16_11 = (delegate*)&Do_Abi_GetChar16_11, - _GetBoolean_12 = (delegate*)&Do_Abi_GetBoolean_12, - _GetString_13 = (delegate*)&Do_Abi_GetString_13, - _GetGuid_14 = (delegate*)&Do_Abi_GetGuid_14, - _GetDateTime_15 = (delegate*)&Do_Abi_GetDateTime_15, - _GetTimeSpan_16 = (delegate*)&Do_Abi_GetTimeSpan_16, - _GetPoint_17 = (delegate*)&Do_Abi_GetPoint_17, - _GetSize_18 = (delegate*)&Do_Abi_GetSize_18, - _GetRect_19 = (delegate*)&Do_Abi_GetRect_19, - _GetUInt8Array_20 = (delegate*)&Do_Abi_GetUInt8Array_20, - _GetInt16Array_21 = (delegate*)&Do_Abi_GetInt16Array_21, - _GetUInt16Array_22 = (delegate*)&Do_Abi_GetUInt16Array_22, - _GetInt32Array_23 = (delegate*)&Do_Abi_GetInt32Array_23, - _GetUInt32Array_24 = (delegate*)&Do_Abi_GetUInt32Array_24, - _GetInt64Array_25 = (delegate*)&Do_Abi_GetInt64Array_25, - _GetUInt64Array_26 = (delegate*)&Do_Abi_GetUInt64Array_26, - _GetSingleArray_27 = (delegate*)&Do_Abi_GetSingleArray_27, - _GetDoubleArray_28 = (delegate*)&Do_Abi_GetDoubleArray_28, - _GetChar16Array_29 = (delegate*)&Do_Abi_GetChar16Array_29, - _GetBooleanArray_30 = (delegate*)&Do_Abi_GetBooleanArray_30, - _GetStringArray_31 = (delegate*)&Do_Abi_GetStringArray_31, - _GetInspectableArray_32 = (delegate*)&Do_Abi_GetInspectableArray_32, - _GetGuidArray_33 = (delegate*)&Do_Abi_GetGuidArray_33, - _GetDateTimeArray_34 = (delegate*)&Do_Abi_GetDateTimeArray_34, - _GetTimeSpanArray_35 = (delegate*)&Do_Abi_GetTimeSpanArray_35, - _GetPointArray_36 = (delegate*)&Do_Abi_GetPointArray_36, - _GetSizeArray_37 = (delegate*)&Do_Abi_GetSizeArray_37, - _GetRectArray_38 = (delegate*)&Do_Abi_GetRectArray_38, -#endif + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + _get_Type_0 = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new IPropertyValue_Delegates.get_Type_0(Do_Abi_get_Type_0)).ToPointer(), + _get_IsNumericScalar_1 = Marshal.GetFunctionPointerForDelegate(DelegateCache[1] = new IPropertyValue_Delegates.get_IsNumericScalar_1(Do_Abi_get_IsNumericScalar_1)).ToPointer(), + _GetUInt8_2 = Marshal.GetFunctionPointerForDelegate(DelegateCache[2] = new IPropertyValue_Delegates.GetUInt8_2(Do_Abi_GetUInt8_2)).ToPointer(), + _GetInt16_3 = Marshal.GetFunctionPointerForDelegate(DelegateCache[3] = new IPropertyValue_Delegates.GetInt16_3(Do_Abi_GetInt16_3)).ToPointer(), + _GetUInt16_4 = Marshal.GetFunctionPointerForDelegate(DelegateCache[4] = new IPropertyValue_Delegates.GetUInt16_4(Do_Abi_GetUInt16_4)).ToPointer(), + _GetInt32_5 = Marshal.GetFunctionPointerForDelegate(DelegateCache[5] = new IPropertyValue_Delegates.GetInt32_5(Do_Abi_GetInt32_5)).ToPointer(), + _GetUInt32_6 = Marshal.GetFunctionPointerForDelegate(DelegateCache[6] = new IPropertyValue_Delegates.GetUInt32_6(Do_Abi_GetUInt32_6)).ToPointer(), + _GetInt64_7 = Marshal.GetFunctionPointerForDelegate(DelegateCache[7] = new IPropertyValue_Delegates.GetInt64_7(Do_Abi_GetInt64_7)).ToPointer(), + _GetUInt64_8 = Marshal.GetFunctionPointerForDelegate(DelegateCache[8] = new IPropertyValue_Delegates.GetUInt64_8(Do_Abi_GetUInt64_8)).ToPointer(), + _GetSingle_9 = Marshal.GetFunctionPointerForDelegate(DelegateCache[9] = new IPropertyValue_Delegates.GetSingle_9(Do_Abi_GetSingle_9)).ToPointer(), + _GetDouble_10 = Marshal.GetFunctionPointerForDelegate(DelegateCache[10] = new IPropertyValue_Delegates.GetDouble_10(Do_Abi_GetDouble_10)).ToPointer(), + _GetChar16_11 = Marshal.GetFunctionPointerForDelegate(DelegateCache[11] = new IPropertyValue_Delegates.GetChar16_11(Do_Abi_GetChar16_11)).ToPointer(), + _GetBoolean_12 = Marshal.GetFunctionPointerForDelegate(DelegateCache[12] = new IPropertyValue_Delegates.GetBoolean_12(Do_Abi_GetBoolean_12)).ToPointer(), + _GetString_13 = Marshal.GetFunctionPointerForDelegate(DelegateCache[13] = new IPropertyValue_Delegates.GetString_13(Do_Abi_GetString_13)).ToPointer(), + _GetGuid_14 = Marshal.GetFunctionPointerForDelegate(DelegateCache[14] = new IPropertyValue_Delegates.GetGuid_14(Do_Abi_GetGuid_14)).ToPointer(), + _GetDateTime_15 = Marshal.GetFunctionPointerForDelegate(DelegateCache[15] = new IPropertyValue_Delegates.GetDateTime_15(Do_Abi_GetDateTime_15)).ToPointer(), + _GetTimeSpan_16 = Marshal.GetFunctionPointerForDelegate(DelegateCache[16] = new IPropertyValue_Delegates.GetTimeSpan_16(Do_Abi_GetTimeSpan_16)).ToPointer(), + _GetPoint_17 = Marshal.GetFunctionPointerForDelegate(DelegateCache[17] = new IPropertyValue_Delegates.GetPoint_17(Do_Abi_GetPoint_17)).ToPointer(), + _GetSize_18 = Marshal.GetFunctionPointerForDelegate(DelegateCache[18] = new IPropertyValue_Delegates.GetSize_18(Do_Abi_GetSize_18)).ToPointer(), + _GetRect_19 = Marshal.GetFunctionPointerForDelegate(DelegateCache[19] = new IPropertyValue_Delegates.GetRect_19(Do_Abi_GetRect_19)).ToPointer(), + _GetUInt8Array_20 = Marshal.GetFunctionPointerForDelegate(DelegateCache[20] = new IPropertyValue_Delegates.GetUInt8Array_20(Do_Abi_GetUInt8Array_20)).ToPointer(), + _GetInt16Array_21 = Marshal.GetFunctionPointerForDelegate(DelegateCache[21] = new IPropertyValue_Delegates.GetInt16Array_21(Do_Abi_GetInt16Array_21)).ToPointer(), + _GetUInt16Array_22 = Marshal.GetFunctionPointerForDelegate(DelegateCache[22] = new IPropertyValue_Delegates.GetUInt16Array_22(Do_Abi_GetUInt16Array_22)).ToPointer(), + _GetInt32Array_23 = Marshal.GetFunctionPointerForDelegate(DelegateCache[23] = new IPropertyValue_Delegates.GetInt32Array_23(Do_Abi_GetInt32Array_23)).ToPointer(), + _GetUInt32Array_24 = Marshal.GetFunctionPointerForDelegate(DelegateCache[24] = new IPropertyValue_Delegates.GetUInt32Array_24(Do_Abi_GetUInt32Array_24)).ToPointer(), + _GetInt64Array_25 = Marshal.GetFunctionPointerForDelegate(DelegateCache[25] = new IPropertyValue_Delegates.GetInt64Array_25(Do_Abi_GetInt64Array_25)).ToPointer(), + _GetUInt64Array_26 = Marshal.GetFunctionPointerForDelegate(DelegateCache[26] = new IPropertyValue_Delegates.GetUInt64Array_26(Do_Abi_GetUInt64Array_26)).ToPointer(), + _GetSingleArray_27 = Marshal.GetFunctionPointerForDelegate(DelegateCache[27] = new IPropertyValue_Delegates.GetSingleArray_27(Do_Abi_GetSingleArray_27)).ToPointer(), + _GetDoubleArray_28 = Marshal.GetFunctionPointerForDelegate(DelegateCache[28] = new IPropertyValue_Delegates.GetDoubleArray_28(Do_Abi_GetDoubleArray_28)).ToPointer(), + _GetChar16Array_29 = Marshal.GetFunctionPointerForDelegate(DelegateCache[29] = new IPropertyValue_Delegates.GetChar16Array_29(Do_Abi_GetChar16Array_29)).ToPointer(), + _GetBooleanArray_30 = Marshal.GetFunctionPointerForDelegate(DelegateCache[30] = new IPropertyValue_Delegates.GetBooleanArray_30(Do_Abi_GetBooleanArray_30)).ToPointer(), + _GetStringArray_31 = Marshal.GetFunctionPointerForDelegate(DelegateCache[31] = new IPropertyValue_Delegates.GetStringArray_31(Do_Abi_GetStringArray_31)).ToPointer(), + _GetInspectableArray_32 = Marshal.GetFunctionPointerForDelegate(DelegateCache[32] = new IPropertyValue_Delegates.GetInspectableArray_32(Do_Abi_GetInspectableArray_32)).ToPointer(), + _GetGuidArray_33 = Marshal.GetFunctionPointerForDelegate(DelegateCache[33] = new IPropertyValue_Delegates.GetGuidArray_33(Do_Abi_GetGuidArray_33)).ToPointer(), + _GetDateTimeArray_34 = Marshal.GetFunctionPointerForDelegate(DelegateCache[34] = new IPropertyValue_Delegates.GetDateTimeArray_34(Do_Abi_GetDateTimeArray_34)).ToPointer(), + _GetTimeSpanArray_35 = Marshal.GetFunctionPointerForDelegate(DelegateCache[35] = new IPropertyValue_Delegates.GetTimeSpanArray_35(Do_Abi_GetTimeSpanArray_35)).ToPointer(), + _GetPointArray_36 = Marshal.GetFunctionPointerForDelegate(DelegateCache[36] = new IPropertyValue_Delegates.GetPointArray_36(Do_Abi_GetPointArray_36)).ToPointer(), + _GetSizeArray_37 = Marshal.GetFunctionPointerForDelegate(DelegateCache[37] = new IPropertyValue_Delegates.GetSizeArray_37(Do_Abi_GetSizeArray_37)).ToPointer(), + _GetRectArray_38 = Marshal.GetFunctionPointerForDelegate(DelegateCache[38] = new IPropertyValue_Delegates.GetRectArray_38(Do_Abi_GetRectArray_38)).ToPointer(), + }; var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(ManagedIPropertyValueImpl), Marshal.SizeOf() + sizeof(IntPtr) * 39); Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); @@ -422,9 +382,7 @@ private static T[] CoerceArray(object value) return coercedArray; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_GetUInt8_2(IntPtr thisPtr, byte* value) { try @@ -437,11 +395,9 @@ private static unsafe int Do_Abi_GetUInt8_2(IntPtr thisPtr, byte* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetInt16_3(IntPtr thisPtr, short* value) { try @@ -454,11 +410,9 @@ private static unsafe int Do_Abi_GetInt16_3(IntPtr thisPtr, short* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetUInt16_4(IntPtr thisPtr, ushort* value) { try @@ -471,11 +425,9 @@ private static unsafe int Do_Abi_GetUInt16_4(IntPtr thisPtr, ushort* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetInt32_5(IntPtr thisPtr, int* value) { try @@ -488,11 +440,9 @@ private static unsafe int Do_Abi_GetInt32_5(IntPtr thisPtr, int* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetUInt32_6(IntPtr thisPtr, uint* value) { try @@ -505,11 +455,9 @@ private static unsafe int Do_Abi_GetUInt32_6(IntPtr thisPtr, uint* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetInt64_7(IntPtr thisPtr, long* value) { try @@ -522,11 +470,9 @@ private static unsafe int Do_Abi_GetInt64_7(IntPtr thisPtr, long* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetUInt64_8(IntPtr thisPtr, ulong* value) { try @@ -539,11 +485,9 @@ private static unsafe int Do_Abi_GetUInt64_8(IntPtr thisPtr, ulong* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetSingle_9(IntPtr thisPtr, float* value) { try @@ -556,11 +500,9 @@ private static unsafe int Do_Abi_GetSingle_9(IntPtr thisPtr, float* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetDouble_10(IntPtr thisPtr, double* value) { try @@ -573,11 +515,9 @@ private static unsafe int Do_Abi_GetDouble_10(IntPtr thisPtr, double* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetChar16_11(IntPtr thisPtr, ushort* value) { @@ -591,11 +531,9 @@ private static unsafe int Do_Abi_GetChar16_11(IntPtr thisPtr, ushort* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetBoolean_12(IntPtr thisPtr, byte* value) { @@ -609,11 +547,9 @@ private static unsafe int Do_Abi_GetBoolean_12(IntPtr thisPtr, byte* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetString_13(IntPtr thisPtr, IntPtr* value) { @@ -627,11 +563,9 @@ private static unsafe int Do_Abi_GetString_13(IntPtr thisPtr, IntPtr* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetGuid_14(IntPtr thisPtr, Guid* value) { @@ -645,11 +579,9 @@ private static unsafe int Do_Abi_GetGuid_14(IntPtr thisPtr, Guid* value) return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetDateTime_15(IntPtr thisPtr, global::ABI.System.DateTimeOffset* value) { @@ -663,11 +595,9 @@ private static unsafe int Do_Abi_GetDateTime_15(IntPtr thisPtr, global::ABI.Syst return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetTimeSpan_16(IntPtr thisPtr, global::ABI.System.TimeSpan* value) { @@ -681,11 +611,9 @@ private static unsafe int Do_Abi_GetTimeSpan_16(IntPtr thisPtr, global::ABI.Syst return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetPoint_17(IntPtr thisPtr, global::Windows.Foundation.Point* value) { @@ -699,11 +627,9 @@ private static unsafe int Do_Abi_GetPoint_17(IntPtr thisPtr, global::Windows.Fou return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetSize_18(IntPtr thisPtr, global::Windows.Foundation.Size* value) { @@ -717,11 +643,9 @@ private static unsafe int Do_Abi_GetSize_18(IntPtr thisPtr, global::Windows.Foun return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetRect_19(IntPtr thisPtr, global::Windows.Foundation.Rect* value) { @@ -735,11 +659,9 @@ private static unsafe int Do_Abi_GetRect_19(IntPtr thisPtr, global::Windows.Foun return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetUInt8Array_20(IntPtr thisPtr, int* __valueSize, IntPtr* value) { byte[] __value = default; @@ -755,11 +677,9 @@ private static unsafe int Do_Abi_GetUInt8Array_20(IntPtr thisPtr, int* __valueSi return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetInt16Array_21(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -778,11 +698,9 @@ private static unsafe int Do_Abi_GetInt16Array_21(IntPtr thisPtr, int* __valueSi return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetUInt16Array_22(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -801,11 +719,9 @@ private static unsafe int Do_Abi_GetUInt16Array_22(IntPtr thisPtr, int* __valueS return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetInt32Array_23(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -824,11 +740,9 @@ private static unsafe int Do_Abi_GetInt32Array_23(IntPtr thisPtr, int* __valueSi return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetUInt32Array_24(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -847,11 +761,9 @@ private static unsafe int Do_Abi_GetUInt32Array_24(IntPtr thisPtr, int* __valueS return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetInt64Array_25(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -870,11 +782,9 @@ private static unsafe int Do_Abi_GetInt64Array_25(IntPtr thisPtr, int* __valueSi return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetUInt64Array_26(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -893,11 +803,9 @@ private static unsafe int Do_Abi_GetUInt64Array_26(IntPtr thisPtr, int* __valueS return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetSingleArray_27(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -916,11 +824,9 @@ private static unsafe int Do_Abi_GetSingleArray_27(IntPtr thisPtr, int* __valueS return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetDoubleArray_28(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -939,11 +845,9 @@ private static unsafe int Do_Abi_GetDoubleArray_28(IntPtr thisPtr, int* __valueS return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetChar16Array_29(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -962,11 +866,9 @@ private static unsafe int Do_Abi_GetChar16Array_29(IntPtr thisPtr, int* __valueS return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetBooleanArray_30(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -985,11 +887,9 @@ private static unsafe int Do_Abi_GetBooleanArray_30(IntPtr thisPtr, int* __value return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetStringArray_31(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -1009,11 +909,9 @@ private static unsafe int Do_Abi_GetStringArray_31(IntPtr thisPtr, int* __valueS return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetInspectableArray_32(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -1032,11 +930,9 @@ private static unsafe int Do_Abi_GetInspectableArray_32(IntPtr thisPtr, int* __v return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetGuidArray_33(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -1056,11 +952,9 @@ private static unsafe int Do_Abi_GetGuidArray_33(IntPtr thisPtr, int* __valueSiz return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetDateTimeArray_34(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -1080,11 +974,9 @@ private static unsafe int Do_Abi_GetDateTimeArray_34(IntPtr thisPtr, int* __valu return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetTimeSpanArray_35(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -1104,11 +996,9 @@ private static unsafe int Do_Abi_GetTimeSpanArray_35(IntPtr thisPtr, int* __valu return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetPointArray_36(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -1128,11 +1018,9 @@ private static unsafe int Do_Abi_GetPointArray_36(IntPtr thisPtr, int* __valueSi return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetSizeArray_37(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -1152,11 +1040,9 @@ private static unsafe int Do_Abi_GetSizeArray_37(IntPtr thisPtr, int* __valueSiz return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_GetRectArray_38(IntPtr thisPtr, int* __valueSize, IntPtr* value) { @@ -1176,11 +1062,9 @@ private static unsafe int Do_Abi_GetRectArray_38(IntPtr thisPtr, int* __valueSiz return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_get_IsNumericScalar_1(IntPtr thisPtr, byte* value) { @@ -1194,11 +1078,9 @@ private static unsafe int Do_Abi_get_IsNumericScalar_1(IntPtr thisPtr, byte* val return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); } return 0; - } - -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + } + + private static unsafe int Do_Abi_get_Type_0(IntPtr thisPtr, global::Windows.Foundation.PropertyType* value) { @@ -1298,84 +1180,84 @@ internal unsafe class IPropertyValue : global::Windows.Foundation.IPropertyValue [Guid("4BD682DD-7554-40E9-9A9B-82654EDE7E62")] public struct Vftbl { - internal IInspectable.Vftbl IInspectableVftbl; - internal void* _get_Type_0; - public delegate* stdcall get_Type_0 { get => (delegate* stdcall)_get_Type_0; set => _get_Type_0 = value; } - public void* _get_IsNumericScalar_1; - public delegate* stdcall get_IsNumericScalar_1 { get => (delegate* stdcall)_get_IsNumericScalar_1; set => _get_IsNumericScalar_1 = value; } - internal void* _GetUInt8_2; - public delegate* stdcall GetUInt8_2 { get => (delegate* stdcall)_GetUInt8_2; set => _GetUInt8_2 = value; } - internal void* _GetInt16_3; - public delegate* stdcall GetInt16_3 { get => (delegate* stdcall)_GetInt16_3; set => _GetInt16_3 = value; } - internal void* _GetUInt16_4; - public delegate* stdcall GetUInt16_4 { get => (delegate* stdcall)_GetUInt16_4; set => _GetUInt16_4 = value; } - internal void* _GetInt32_5; - public delegate* stdcall GetInt32_5 { get => (delegate* stdcall)_GetInt32_5; set => _GetInt32_5 = value; } - internal void* _GetUInt32_6; - public delegate* stdcall GetUInt32_6 { get => (delegate* stdcall)_GetUInt32_6; set => _GetUInt32_6 = value; } - internal void* _GetInt64_7; - public delegate* stdcall GetInt64_7 { get => (delegate* stdcall)_GetInt64_7; set => _GetInt64_7 = value; } - internal void* _GetUInt64_8; - public delegate* stdcall GetUInt64_8 { get => (delegate* stdcall)_GetUInt64_8; set => _GetUInt64_8 = value; } - internal void* _GetSingle_9; - public delegate* stdcall GetSingle_9 { get => (delegate* stdcall)_GetSingle_9; set => _GetSingle_9 = value; } - internal void* _GetDouble_10; - public delegate* stdcall GetDouble_10 { get => (delegate* stdcall)_GetDouble_10; set => _GetDouble_10 = value; } - internal void* _GetChar16_11; - public delegate* stdcall GetChar16_11 { get => (delegate* stdcall)_GetChar16_11; set => _GetChar16_11 = value; } - internal void* _GetBoolean_12; - public delegate* stdcall GetBoolean_12 { get => (delegate* stdcall)_GetBoolean_12; set => _GetBoolean_12 = value; } - internal void* _GetString_13; - public delegate* stdcall GetString_13 { get => (delegate* stdcall)_GetString_13; set => _GetString_13 = value; } - internal void* _GetGuid_14; - public delegate* stdcall GetGuid_14 { get => (delegate* stdcall)_GetGuid_14; set => _GetGuid_14 = value; } - internal void* _GetDateTime_15; - public delegate* stdcall GetDateTime_15 { get => (delegate* stdcall)_GetDateTime_15; set => _GetDateTime_15 = value; } - internal void* _GetTimeSpan_16; - public delegate* stdcall GetTimeSpan_16 { get => (delegate* stdcall)_GetTimeSpan_16; set => _GetTimeSpan_16 = value; } - internal void* _GetPoint_17; - public delegate* stdcall GetPoint_17 { get => (delegate* stdcall)_GetPoint_17; set => _GetPoint_17 = value; } - internal void* _GetSize_18; - public delegate* stdcall GetSize_18 { get => (delegate* stdcall)_GetSize_18; set => _GetSize_18 = value; } - internal void* _GetRect_19; - public delegate* stdcall GetRect_19 { get => (delegate* stdcall)_GetRect_19; set => _GetRect_19 = value; } - internal void* _GetUInt8Array_20; - public delegate* stdcall GetUInt8Array_20 { get => (delegate* stdcall)_GetUInt8Array_20; set => _GetUInt8Array_20 = value; } - internal void* _GetInt16Array_21; - public delegate* stdcall GetInt16Array_21 { get => (delegate* stdcall)_GetInt16Array_21; set => _GetInt16Array_21 = value; } - internal void* _GetUInt16Array_22; - public delegate* stdcall GetUInt16Array_22 { get => (delegate* stdcall)_GetUInt16Array_22; set => _GetUInt16Array_22 = value; } - internal void* _GetInt32Array_23; - public delegate* stdcall GetInt32Array_23 { get => (delegate* stdcall)_GetInt32Array_23; set => _GetInt32Array_23 = value; } - internal void* _GetUInt32Array_24; - public delegate* stdcall GetUInt32Array_24 { get => (delegate* stdcall)_GetUInt32Array_24; set => _GetUInt32Array_24 = value; } - internal void* _GetInt64Array_25; - public delegate* stdcall GetInt64Array_25 { get => (delegate* stdcall)_GetInt64Array_25; set => _GetInt64Array_25 = value; } - internal void* _GetUInt64Array_26; - public delegate* stdcall GetUInt64Array_26 { get => (delegate* stdcall)_GetUInt64Array_26; set => _GetUInt64Array_26 = value; } - internal void* _GetSingleArray_27; - public delegate* stdcall GetSingleArray_27 { get => (delegate* stdcall)_GetSingleArray_27; set => _GetSingleArray_27 = value; } - internal void* _GetDoubleArray_28; - public delegate* stdcall GetDoubleArray_28 { get => (delegate* stdcall)_GetDoubleArray_28; set => _GetDoubleArray_28 = value; } - internal void* _GetChar16Array_29; - public delegate* stdcall GetChar16Array_29 { get => (delegate* stdcall)_GetChar16Array_29; set => _GetChar16Array_29 = value; } - internal void* _GetBooleanArray_30; - public delegate* stdcall GetBooleanArray_30 { get => (delegate* stdcall)_GetBooleanArray_30; set => _GetBooleanArray_30 = value; } - internal void* _GetStringArray_31; - public delegate* stdcall GetStringArray_31 { get => (delegate* stdcall)_GetStringArray_31; set => _GetStringArray_31 = value; } - internal void* _GetInspectableArray_32; - public delegate* stdcall GetInspectableArray_32 { get => (delegate* stdcall)_GetInspectableArray_32; set => _GetInspectableArray_32 = value; } - internal void* _GetGuidArray_33; - public delegate* stdcall GetGuidArray_33 { get => (delegate* stdcall)_GetGuidArray_33; set => _GetGuidArray_33 = value; } - internal void* _GetDateTimeArray_34; - public delegate* stdcall GetDateTimeArray_34 { get => (delegate* stdcall)_GetDateTimeArray_34; set => _GetDateTimeArray_34 = value; } - internal void* _GetTimeSpanArray_35; - public delegate* stdcall GetTimeSpanArray_35 { get => (delegate* stdcall)_GetTimeSpanArray_35; set => _GetTimeSpanArray_35 = value; } - internal void* _GetPointArray_36; - public delegate* stdcall GetPointArray_36 { get => (delegate* stdcall)_GetPointArray_36; set => _GetPointArray_36 = value; } - internal void* _GetSizeArray_37; - public delegate* stdcall GetSizeArray_37 { get => (delegate* stdcall)_GetSizeArray_37; set => _GetSizeArray_37 = value; } - internal void* _GetRectArray_38; + internal IInspectable.Vftbl IInspectableVftbl; + internal void* _get_Type_0; + public delegate* stdcall get_Type_0 { get => (delegate* stdcall)_get_Type_0; set => _get_Type_0 = value; } + public void* _get_IsNumericScalar_1; + public delegate* stdcall get_IsNumericScalar_1 { get => (delegate* stdcall)_get_IsNumericScalar_1; set => _get_IsNumericScalar_1 = value; } + internal void* _GetUInt8_2; + public delegate* stdcall GetUInt8_2 { get => (delegate* stdcall)_GetUInt8_2; set => _GetUInt8_2 = value; } + internal void* _GetInt16_3; + public delegate* stdcall GetInt16_3 { get => (delegate* stdcall)_GetInt16_3; set => _GetInt16_3 = value; } + internal void* _GetUInt16_4; + public delegate* stdcall GetUInt16_4 { get => (delegate* stdcall)_GetUInt16_4; set => _GetUInt16_4 = value; } + internal void* _GetInt32_5; + public delegate* stdcall GetInt32_5 { get => (delegate* stdcall)_GetInt32_5; set => _GetInt32_5 = value; } + internal void* _GetUInt32_6; + public delegate* stdcall GetUInt32_6 { get => (delegate* stdcall)_GetUInt32_6; set => _GetUInt32_6 = value; } + internal void* _GetInt64_7; + public delegate* stdcall GetInt64_7 { get => (delegate* stdcall)_GetInt64_7; set => _GetInt64_7 = value; } + internal void* _GetUInt64_8; + public delegate* stdcall GetUInt64_8 { get => (delegate* stdcall)_GetUInt64_8; set => _GetUInt64_8 = value; } + internal void* _GetSingle_9; + public delegate* stdcall GetSingle_9 { get => (delegate* stdcall)_GetSingle_9; set => _GetSingle_9 = value; } + internal void* _GetDouble_10; + public delegate* stdcall GetDouble_10 { get => (delegate* stdcall)_GetDouble_10; set => _GetDouble_10 = value; } + internal void* _GetChar16_11; + public delegate* stdcall GetChar16_11 { get => (delegate* stdcall)_GetChar16_11; set => _GetChar16_11 = value; } + internal void* _GetBoolean_12; + public delegate* stdcall GetBoolean_12 { get => (delegate* stdcall)_GetBoolean_12; set => _GetBoolean_12 = value; } + internal void* _GetString_13; + public delegate* stdcall GetString_13 { get => (delegate* stdcall)_GetString_13; set => _GetString_13 = value; } + internal void* _GetGuid_14; + public delegate* stdcall GetGuid_14 { get => (delegate* stdcall)_GetGuid_14; set => _GetGuid_14 = value; } + internal void* _GetDateTime_15; + public delegate* stdcall GetDateTime_15 { get => (delegate* stdcall)_GetDateTime_15; set => _GetDateTime_15 = value; } + internal void* _GetTimeSpan_16; + public delegate* stdcall GetTimeSpan_16 { get => (delegate* stdcall)_GetTimeSpan_16; set => _GetTimeSpan_16 = value; } + internal void* _GetPoint_17; + public delegate* stdcall GetPoint_17 { get => (delegate* stdcall)_GetPoint_17; set => _GetPoint_17 = value; } + internal void* _GetSize_18; + public delegate* stdcall GetSize_18 { get => (delegate* stdcall)_GetSize_18; set => _GetSize_18 = value; } + internal void* _GetRect_19; + public delegate* stdcall GetRect_19 { get => (delegate* stdcall)_GetRect_19; set => _GetRect_19 = value; } + internal void* _GetUInt8Array_20; + public delegate* stdcall GetUInt8Array_20 { get => (delegate* stdcall)_GetUInt8Array_20; set => _GetUInt8Array_20 = value; } + internal void* _GetInt16Array_21; + public delegate* stdcall GetInt16Array_21 { get => (delegate* stdcall)_GetInt16Array_21; set => _GetInt16Array_21 = value; } + internal void* _GetUInt16Array_22; + public delegate* stdcall GetUInt16Array_22 { get => (delegate* stdcall)_GetUInt16Array_22; set => _GetUInt16Array_22 = value; } + internal void* _GetInt32Array_23; + public delegate* stdcall GetInt32Array_23 { get => (delegate* stdcall)_GetInt32Array_23; set => _GetInt32Array_23 = value; } + internal void* _GetUInt32Array_24; + public delegate* stdcall GetUInt32Array_24 { get => (delegate* stdcall)_GetUInt32Array_24; set => _GetUInt32Array_24 = value; } + internal void* _GetInt64Array_25; + public delegate* stdcall GetInt64Array_25 { get => (delegate* stdcall)_GetInt64Array_25; set => _GetInt64Array_25 = value; } + internal void* _GetUInt64Array_26; + public delegate* stdcall GetUInt64Array_26 { get => (delegate* stdcall)_GetUInt64Array_26; set => _GetUInt64Array_26 = value; } + internal void* _GetSingleArray_27; + public delegate* stdcall GetSingleArray_27 { get => (delegate* stdcall)_GetSingleArray_27; set => _GetSingleArray_27 = value; } + internal void* _GetDoubleArray_28; + public delegate* stdcall GetDoubleArray_28 { get => (delegate* stdcall)_GetDoubleArray_28; set => _GetDoubleArray_28 = value; } + internal void* _GetChar16Array_29; + public delegate* stdcall GetChar16Array_29 { get => (delegate* stdcall)_GetChar16Array_29; set => _GetChar16Array_29 = value; } + internal void* _GetBooleanArray_30; + public delegate* stdcall GetBooleanArray_30 { get => (delegate* stdcall)_GetBooleanArray_30; set => _GetBooleanArray_30 = value; } + internal void* _GetStringArray_31; + public delegate* stdcall GetStringArray_31 { get => (delegate* stdcall)_GetStringArray_31; set => _GetStringArray_31 = value; } + internal void* _GetInspectableArray_32; + public delegate* stdcall GetInspectableArray_32 { get => (delegate* stdcall)_GetInspectableArray_32; set => _GetInspectableArray_32 = value; } + internal void* _GetGuidArray_33; + public delegate* stdcall GetGuidArray_33 { get => (delegate* stdcall)_GetGuidArray_33; set => _GetGuidArray_33 = value; } + internal void* _GetDateTimeArray_34; + public delegate* stdcall GetDateTimeArray_34 { get => (delegate* stdcall)_GetDateTimeArray_34; set => _GetDateTimeArray_34 = value; } + internal void* _GetTimeSpanArray_35; + public delegate* stdcall GetTimeSpanArray_35 { get => (delegate* stdcall)_GetTimeSpanArray_35; set => _GetTimeSpanArray_35 = value; } + internal void* _GetPointArray_36; + public delegate* stdcall GetPointArray_36 { get => (delegate* stdcall)_GetPointArray_36; set => _GetPointArray_36 = value; } + internal void* _GetSizeArray_37; + public delegate* stdcall GetSizeArray_37 { get => (delegate* stdcall)_GetSizeArray_37; set => _GetSizeArray_37 = value; } + internal void* _GetRectArray_38; public delegate* stdcall GetRectArray_38 { get => (delegate* stdcall)_GetRectArray_38; set => _GetRectArray_38 = value; } } diff --git a/WinRT.Runtime/Projections/IReadOnlyDictionary.net5.cs b/WinRT.Runtime/Projections/IReadOnlyDictionary.net5.cs new file mode 100644 index 000000000..2c188661c --- /dev/null +++ b/WinRT.Runtime/Projections/IReadOnlyDictionary.net5.cs @@ -0,0 +1,694 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; +using System.Diagnostics; + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Windows.Foundation.Collections +{ + [Guid("E480CE40-A338-4ADA-ADCF-272272E48CB9")] + interface IMapView : IIterable> + { + V Lookup(K key); + bool HasKey(K key); + void Split(out IMapView first, out IMapView second); + uint Size { get; } + } +} + +namespace ABI.System.Collections.Generic +{ + using global::System; + using global::System.Runtime.CompilerServices; + + [DynamicInterfaceCastableImplementation] + [Guid("E480CE40-A338-4ADA-ADCF-272272E48CB9")] + interface IReadOnlyDictionary : global::System.Collections.Generic.IReadOnlyDictionary, global::Windows.Foundation.Collections.IMapView + { + public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IReadOnlyDictionary obj) => + obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IReadOnlyDictionary))); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static IntPtr FromManaged(global::System.Collections.Generic.IReadOnlyDictionary value) => + (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); + + public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IReadOnlyDictionary)); + + public class FromAbiHelper : global::System.Collections.Generic.IReadOnlyDictionary + { + private readonly global::Windows.Foundation.Collections.IMapView _mapView; + private readonly global::System.Collections.Generic.IEnumerable> _enumerable; + + public FromAbiHelper(global::Windows.Foundation.Collections.IMapView mapView, ObjectReference objRef) + { + _mapView = mapView; + _enumerable = (System.Collections.Generic.IEnumerable>)new IInspectable(objRef); + } + + public int Count + { + get + { + uint size = _mapView.Size; + + if (((uint)int.MaxValue) < size) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingDictionaryTooLarge); + } + + return (int)size; + } + } + + public V this[K key] { get => Indexer_Get(key); } + + private V Indexer_Get(K key) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + return Lookup(_mapView, key); + } + + public global::System.Collections.Generic.IEnumerable Keys + { + get => new ReadOnlyDictionaryKeyCollection(this); + } + + public global::System.Collections.Generic.IEnumerable Values + { + get => new ReadOnlyDictionaryValueCollection(this); + } + + public bool ContainsKey(K key) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + return _mapView.HasKey(key); + } + + public bool TryGetValue(K key, out V value) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + + // It may be faster to call HasKey then Lookup. On failure, we would otherwise + // throw an exception from Lookup. + if (!_mapView.HasKey(key)) + { + value = default!; + return false; + } + + try + { + value = _mapView.Lookup(key); + return true; + } + catch (Exception ex) // Still may hit this case due to a race condition + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + { + value = default!; + return false; + } + throw; + } + } + + private static V Lookup(global::Windows.Foundation.Collections.IMapView _this, K key) + { + try + { + return _this.Lookup(key); + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); + throw; + } + } + + public global::System.Collections.Generic.IEnumerator> GetEnumerator() => _enumerable.GetEnumerator(); + + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + + private sealed class ReadOnlyDictionaryKeyCollection : global::System.Collections.Generic.IEnumerable + { + private readonly global::System.Collections.Generic.IReadOnlyDictionary dictionary; + + public ReadOnlyDictionaryKeyCollection(global::System.Collections.Generic.IReadOnlyDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + } + + public global::System.Collections.Generic.IEnumerator GetEnumerator() + { + return new ReadOnlyDictionaryKeyEnumerator(dictionary); + } + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + + private sealed class ReadOnlyDictionaryKeyEnumerator : global::System.Collections.Generic.IEnumerator + { + private readonly global::System.Collections.Generic.IReadOnlyDictionary dictionary; + private global::System.Collections.Generic.IEnumerator> enumeration; + + public ReadOnlyDictionaryKeyEnumerator(global::System.Collections.Generic.IReadOnlyDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + enumeration = dictionary.GetEnumerator(); + } + + void IDisposable.Dispose() + { + enumeration.Dispose(); + } + + public bool MoveNext() + { + return enumeration.MoveNext(); + } + + object IEnumerator.Current => Current; + + public K Current => enumeration.Current.Key; + + public void Reset() + { + enumeration = dictionary.GetEnumerator(); + } + } + } + + private sealed class ReadOnlyDictionaryValueCollection : global::System.Collections.Generic.IEnumerable + { + private readonly global::System.Collections.Generic.IReadOnlyDictionary dictionary; + + public ReadOnlyDictionaryValueCollection(global::System.Collections.Generic.IReadOnlyDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + } + + public global::System.Collections.Generic.IEnumerator GetEnumerator() + { + return new ReadOnlyDictionaryValueEnumerator(dictionary); + } + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + + private sealed class ReadOnlyDictionaryValueEnumerator : global::System.Collections.Generic.IEnumerator + { + private readonly global::System.Collections.Generic.IReadOnlyDictionary dictionary; + private global::System.Collections.Generic.IEnumerator> enumeration; + + public ReadOnlyDictionaryValueEnumerator(global::System.Collections.Generic.IReadOnlyDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + enumeration = dictionary.GetEnumerator(); + } + + void IDisposable.Dispose() + { + enumeration.Dispose(); + } + + public bool MoveNext() + { + return enumeration.MoveNext(); + } + + object IEnumerator.Current => Current; + + public V Current => enumeration.Current.Value; + + public void Reset() + { + enumeration = dictionary.GetEnumerator(); + } + } + } + } + + public class ToAbiHelper : global::Windows.Foundation.Collections.IMapView + { + private readonly global::System.Collections.Generic.IReadOnlyDictionary _dictionary; + + internal ToAbiHelper(global::System.Collections.Generic.IReadOnlyDictionary dictionary) => _dictionary = dictionary; + + uint global::Windows.Foundation.Collections.IMapView.Size { get => (uint)_dictionary.Count; } + + global::Windows.Foundation.Collections.IIterator> global::Windows.Foundation.Collections.IIterable>.First() => + new IEnumerator>.ToAbiHelper( + new KeyValuePair.Enumerator(_dictionary.GetEnumerator())); + + public V Lookup(K key) + { + V value; + bool keyFound = _dictionary.TryGetValue(key, out value); + + if (!keyFound) + { + Exception e = new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + + return value; + } + + public uint Size() => (uint)_dictionary.Count; + + public bool HasKey(K key) => _dictionary.ContainsKey(key); + + void global::Windows.Foundation.Collections.IMapView.Split(out global::Windows.Foundation.Collections.IMapView first, out global::Windows.Foundation.Collections.IMapView second) + { + if (_dictionary.Count < 2) + { + first = null; + second = null; + return; + } + + if (!(_dictionary is ConstantSplittableMap splittableMap)) + splittableMap = new ConstantSplittableMap(_dictionary); + + splittableMap.Split(out first, out second); + } + + private sealed class ConstantSplittableMap : global::Windows.Foundation.Collections.IMapView + { + private class KeyValuePairComparator : IComparer> + { + private static readonly IComparer keyComparator = Comparer.Default; + + public int Compare(global::System.Collections.Generic.KeyValuePair x, global::System.Collections.Generic.KeyValuePair y) + { + return keyComparator.Compare(x.Key, y.Key); + } + } + + private static readonly KeyValuePairComparator keyValuePairComparator = new KeyValuePairComparator(); + + private readonly global::System.Collections.Generic.KeyValuePair[] items; + private readonly int firstItemIndex; + private readonly int lastItemIndex; + + internal ConstantSplittableMap(global::System.Collections.Generic.IReadOnlyDictionary data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + + firstItemIndex = 0; + lastItemIndex = data.Count - 1; + items = CreateKeyValueArray(data.Count, data.GetEnumerator()); + } + + private ConstantSplittableMap(global::System.Collections.Generic.KeyValuePair[] items, int firstItemIndex, int lastItemIndex) + { + this.items = items; + this.firstItemIndex = firstItemIndex; + this.lastItemIndex = lastItemIndex; + } + + private global::System.Collections.Generic.KeyValuePair[] CreateKeyValueArray(int count, global::System.Collections.Generic.IEnumerator> data) + { + global::System.Collections.Generic.KeyValuePair[] kvArray = new global::System.Collections.Generic.KeyValuePair[count]; + + int i = 0; + while (data.MoveNext()) + kvArray[i++] = data.Current; + + Array.Sort(kvArray, keyValuePairComparator); + + return kvArray; + } + + public int Count => lastItemIndex - firstItemIndex + 1; + + public uint Size => (uint)(lastItemIndex - firstItemIndex + 1); + + public V Lookup(K key) + { + V value; + bool found = TryGetValue(key, out value); + + if (!found) + { + Exception e = new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + + return value; + } + + public bool HasKey(K key) => + TryGetValue(key, out _); + + public global::Windows.Foundation.Collections.IIterator> First() => + new IEnumerator>.ToAbiHelper(GetEnumerator()); + + private global::System.Collections.Generic.IEnumerator> GetEnumerator() => + new Enumerator(items, firstItemIndex, lastItemIndex); + + public void Split(out global::Windows.Foundation.Collections.IMapView firstPartition, out global::Windows.Foundation.Collections.IMapView secondPartition) + { + if (Count < 2) + { + firstPartition = null; + secondPartition = null; + return; + } + + int pivot = (int)(((long)firstItemIndex + (long)lastItemIndex) / (long)2); + + firstPartition = new ConstantSplittableMap(items, firstItemIndex, pivot); + secondPartition = new ConstantSplittableMap(items, pivot + 1, lastItemIndex); + } + + public bool TryGetValue(K key, out V value) + { + var searchKey = new global::System.Collections.Generic.KeyValuePair(key, default!); + int index = Array.BinarySearch(items, firstItemIndex, Count, searchKey, keyValuePairComparator); + + if (index < 0) + { + value = default!; + return false; + } + + value = items[index].Value; + return true; + } + } + + internal struct Enumerator : global::System.Collections.Generic.IEnumerator> + { + private readonly global::System.Collections.Generic.KeyValuePair[] _array; + private readonly int _start; + private readonly int _end; + private int _current; + + internal Enumerator(global::System.Collections.Generic.KeyValuePair[] items, int first, int end) + { + _array = items; + _start = first; + _end = end; + _current = _start - 1; + } + + public bool MoveNext() + { + if (_current < _end) + { + _current++; + return true; + } + return false; + } + + public global::Windows.Foundation.Collections.IKeyValuePair Current + { + get + { + if (_current < _start) throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumNotStarted); + if (_current > _end) throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumEnded); + return new KeyValuePair.ToIKeyValuePair(ref _array[_current]); + } + } + + object IEnumerator.Current => Current; + + void IEnumerator.Reset() => + _current = _start - 1; + + public void Dispose() + { + } + } + } + + [Guid("E480CE40-A338-4ADA-ADCF-272272E48CB9")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate Lookup_0; + internal _get_PropertyAsUInt32 get_Size_1; + public global::System.Delegate HasKey_2; + public IReadOnlyDictionary_Delegates.Split_3 Split_3; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IReadOnlyDictionary)); + private static readonly Type Lookup_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, Marshaler.AbiType.MakeByRefType(), typeof(int) }); + private static readonly Type HasKey_2_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(byte).MakeByRefType(), typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + Lookup_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], Lookup_0_Type); + get_Size_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsUInt32>(vftbl[7]); + HasKey_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8], HasKey_2_Type); + Split_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9]); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + Lookup_0 = global::System.Delegate.CreateDelegate(Lookup_0_Type, typeof(Vftbl).GetMethod("Do_Abi_Lookup_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType, Marshaler.AbiType)), + get_Size_1 = Do_Abi_get_Size_1, + HasKey_2 = global::System.Delegate.CreateDelegate(HasKey_2_Type, typeof(Vftbl).GetMethod("Do_Abi_HasKey_2", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + Split_3 = Do_Abi_Split_3 + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 4); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Lookup_0); + nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Size_1); + nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.HasKey_2); + nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Split_3); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable, ToAbiHelper> _adapterTable = + new ConditionalWeakTable, ToAbiHelper>(); + + private static global::Windows.Foundation.Collections.IMapView FindAdapter(IntPtr thisPtr) + { + var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); + return _adapterTable.GetValue(__this, (dictionary) => new ToAbiHelper(dictionary)); + } + + private static unsafe int Do_Abi_Lookup_0(void* thisPtr, KAbi key, out VAbi __return_value__) + { + V ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Lookup(Marshaler.FromAbi(key)); + __return_value__ = (VAbi)Marshaler.FromManaged(____return_value__); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_HasKey_2(void* thisPtr, KAbi key, out byte __return_value__) + { + bool ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).HasKey(Marshaler.FromAbi(key)); + __return_value__ = (byte)(____return_value__ ? 1 : 0); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_Split_3(IntPtr thisPtr, out IntPtr first, out IntPtr second) + { + + first = default; + second = default; + global::Windows.Foundation.Collections.IMapView __first = default; + global::Windows.Foundation.Collections.IMapView __second = default; + + try + { + FindAdapter(thisPtr).Split(out __first, out __second); + first = MarshalInterface>.FromManaged(__first); + second = MarshalInterface>.FromManaged(__second); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).Size; + __return_value__ = ____return_value__; + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + public static Guid PIID = Vftbl.PIID; + + private static FromAbiHelper _FromMapView(IWinRTObject _this) + { + var _obj = ((ObjectReference)_this.GetObjectReferenceForType(typeof(global::System.Collections.Generic.IReadOnlyDictionary).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + return (FromAbiHelper)_this.GetOrCreateTypeHelperData(typeof(global::System.Collections.Generic.IReadOnlyDictionary).TypeHandle, + () => new FromAbiHelper((global::Windows.Foundation.Collections.IMapView)_this, _obj)); + } + + unsafe V global::Windows.Foundation.Collections.IMapView.Lookup(K key) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IReadOnlyDictionary).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + object __key = default; + var __params = new object[] { ThisPtr, null, null }; + try + { + __key = Marshaler.CreateMarshaler(key); + __params[1] = Marshaler.GetAbi(__key); + _obj.Vftbl.Lookup_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[2]); + } + finally + { + Marshaler.DisposeMarshaler(__key); + Marshaler.DisposeAbi(__params[2]); + } + } + + unsafe bool global::Windows.Foundation.Collections.IMapView.HasKey(K key) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IReadOnlyDictionary).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + object __key = default; + var __params = new object[] { ThisPtr, null, null }; + try + { + __key = Marshaler.CreateMarshaler(key); + __params[1] = Marshaler.GetAbi(__key); + _obj.Vftbl.HasKey_2.DynamicInvokeAbi(__params); + return (byte)__params[2] != 0; + } + finally + { + Marshaler.DisposeMarshaler(__key); + } + } + + unsafe void global::Windows.Foundation.Collections.IMapView.Split(out global::Windows.Foundation.Collections.IMapView first, out global::Windows.Foundation.Collections.IMapView second) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IReadOnlyDictionary).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + IntPtr __first = default; + IntPtr __second = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Split_3(ThisPtr, out __first, out __second)); + first = MarshalInterface>.FromAbi(__first); + second = MarshalInterface>.FromAbi(__second); + } + finally + { + MarshalInterface>.DisposeAbi(__first); + MarshalInterface>.DisposeAbi(__second); + } + } + + unsafe uint global::Windows.Foundation.Collections.IMapView.Size + { + get + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IReadOnlyDictionary).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + uint __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, out __retval)); + return __retval; + } + } + + global::System.Collections.Generic.IEnumerable global::System.Collections.Generic.IReadOnlyDictionary.Keys => _FromMapView((IWinRTObject)this).Keys; + global::System.Collections.Generic.IEnumerable global::System.Collections.Generic.IReadOnlyDictionary.Values => _FromMapView((IWinRTObject)this).Values; + int global::System.Collections.Generic.IReadOnlyCollection>.Count => _FromMapView((IWinRTObject)this).Count; + V global::System.Collections.Generic.IReadOnlyDictionary.this[K key] => _FromMapView((IWinRTObject)this)[key]; + bool global::System.Collections.Generic.IReadOnlyDictionary.ContainsKey(K key) => _FromMapView((IWinRTObject)this).ContainsKey(key); + bool global::System.Collections.Generic.IReadOnlyDictionary.TryGetValue(K key, out V value) => _FromMapView((IWinRTObject)this).TryGetValue(key, out value); + 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 + { + public unsafe delegate int Split_3(IntPtr thisPtr, out IntPtr first, out IntPtr second); + } +} diff --git a/WinRT.Runtime/Projections/IReadOnlyDictionary.cs b/WinRT.Runtime/Projections/IReadOnlyDictionary.netstandard2.0.cs similarity index 97% rename from WinRT.Runtime/Projections/IReadOnlyDictionary.cs rename to WinRT.Runtime/Projections/IReadOnlyDictionary.netstandard2.0.cs index e536e6504..fbb67fb9e 100644 --- a/WinRT.Runtime/Projections/IReadOnlyDictionary.cs +++ b/WinRT.Runtime/Projections/IReadOnlyDictionary.netstandard2.0.cs @@ -1,696 +1,696 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.InteropServices; -using WinRT; -using WinRT.Interop; -using System.Diagnostics; - -#pragma warning disable 0169 // warning CS0169: The field '...' is never used -#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to - -namespace Windows.Foundation.Collections -{ - [Guid("E480CE40-A338-4ADA-ADCF-272272E48CB9")] - interface IMapView : IIterable> - { - V Lookup(K key); - bool HasKey(K key); - void Split(out IMapView first, out IMapView second); - uint Size { get; } - } -} - -namespace ABI.System.Collections.Generic -{ - using global::System; - using global::System.Runtime.CompilerServices; - - [Guid("E480CE40-A338-4ADA-ADCF-272272E48CB9")] - public 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))); - - public static IntPtr GetAbi(IObjectReference objRef) => - objRef?.ThisPtr ?? IntPtr.Zero; - - public static global::System.Collections.Generic.IReadOnlyDictionary FromAbi(IntPtr thisPtr) => - thisPtr == IntPtr.Zero ? null : new IReadOnlyDictionary(ObjRefFromAbi(thisPtr)); - - public static IntPtr FromManaged(global::System.Collections.Generic.IReadOnlyDictionary value) => - (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); - - public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); - - public static void DisposeAbi(IntPtr abi) => - MarshalInterfaceHelper>.DisposeAbi(abi); - - public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IReadOnlyDictionary)); - - public class FromAbiHelper : global::System.Collections.Generic.IReadOnlyDictionary - { - private readonly global::ABI.System.Collections.Generic.IReadOnlyDictionary _mapView; - private readonly global::ABI.System.Collections.Generic.IEnumerable> _enumerable; - - public FromAbiHelper(IObjectReference obj) : - this(new global::ABI.System.Collections.Generic.IReadOnlyDictionary(obj)) - { - } - - public FromAbiHelper(global::ABI.System.Collections.Generic.IReadOnlyDictionary mapView) - { - _mapView = mapView; - _enumerable = new ABI.System.Collections.Generic.IEnumerable>(mapView.ObjRef); - } - - public int Count - { - get - { - uint size = _mapView.Size; - - if (((uint)int.MaxValue) < size) - { - throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingDictionaryTooLarge); - } - - return (int)size; - } - } - - public V this[K key] { get => Indexer_Get(key); } - - private V Indexer_Get(K key) - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - return Lookup(_mapView, key); - } - - public global::System.Collections.Generic.IEnumerable Keys - { - get => new ReadOnlyDictionaryKeyCollection(this); - } - - public global::System.Collections.Generic.IEnumerable Values - { - get => new ReadOnlyDictionaryValueCollection(this); - } - - public bool ContainsKey(K key) - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - return _mapView.HasKey(key); - } - - public bool TryGetValue(K key, out V value) - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - // It may be faster to call HasKey then Lookup. On failure, we would otherwise - // throw an exception from Lookup. - if (!_mapView.HasKey(key)) - { - value = default!; - return false; - } - - try - { - value = _mapView.Lookup(key); - return true; - } - catch (Exception ex) // Still may hit this case due to a race condition - { - if (ExceptionHelpers.E_BOUNDS == ex.HResult) - { - value = default!; - return false; - } - throw; - } - } - - private static V Lookup(global::ABI.System.Collections.Generic.IReadOnlyDictionary _this, K key) - { - try - { - return _this.Lookup(key); - } - catch (Exception ex) - { - if (ExceptionHelpers.E_BOUNDS == ex.HResult) - throw new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); - throw; - } - } - - public global::System.Collections.Generic.IEnumerator> GetEnumerator() => _enumerable.GetEnumerator(); - - IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - - private sealed class ReadOnlyDictionaryKeyCollection : global::System.Collections.Generic.IEnumerable - { - private readonly global::System.Collections.Generic.IReadOnlyDictionary dictionary; - - public ReadOnlyDictionaryKeyCollection(global::System.Collections.Generic.IReadOnlyDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - } - - public global::System.Collections.Generic.IEnumerator GetEnumerator() - { - return new ReadOnlyDictionaryKeyEnumerator(dictionary); - } - IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - - private sealed class ReadOnlyDictionaryKeyEnumerator : global::System.Collections.Generic.IEnumerator - { - private readonly global::System.Collections.Generic.IReadOnlyDictionary dictionary; - private global::System.Collections.Generic.IEnumerator> enumeration; - - public ReadOnlyDictionaryKeyEnumerator(global::System.Collections.Generic.IReadOnlyDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - enumeration = dictionary.GetEnumerator(); - } - - void IDisposable.Dispose() - { - enumeration.Dispose(); - } - - public bool MoveNext() - { - return enumeration.MoveNext(); - } - - object IEnumerator.Current => Current; - - public K Current => enumeration.Current.Key; - - public void Reset() - { - enumeration = dictionary.GetEnumerator(); - } - } - } - - private sealed class ReadOnlyDictionaryValueCollection : global::System.Collections.Generic.IEnumerable - { - private readonly global::System.Collections.Generic.IReadOnlyDictionary dictionary; - - public ReadOnlyDictionaryValueCollection(global::System.Collections.Generic.IReadOnlyDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - } - - public global::System.Collections.Generic.IEnumerator GetEnumerator() - { - return new ReadOnlyDictionaryValueEnumerator(dictionary); - } - global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - - private sealed class ReadOnlyDictionaryValueEnumerator : global::System.Collections.Generic.IEnumerator - { - private readonly global::System.Collections.Generic.IReadOnlyDictionary dictionary; - private global::System.Collections.Generic.IEnumerator> enumeration; - - public ReadOnlyDictionaryValueEnumerator(global::System.Collections.Generic.IReadOnlyDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - enumeration = dictionary.GetEnumerator(); - } - - void IDisposable.Dispose() - { - enumeration.Dispose(); - } - - public bool MoveNext() - { - return enumeration.MoveNext(); - } - - object IEnumerator.Current => Current; - - public V Current => enumeration.Current.Value; - - public void Reset() - { - enumeration = dictionary.GetEnumerator(); - } - } - } - } - - public class ToAbiHelper : global::Windows.Foundation.Collections.IMapView - { - private readonly global::System.Collections.Generic.IReadOnlyDictionary _dictionary; - - internal ToAbiHelper(global::System.Collections.Generic.IReadOnlyDictionary dictionary) => _dictionary = dictionary; - - uint global::Windows.Foundation.Collections.IMapView.Size { get => (uint)_dictionary.Count; } - - global::Windows.Foundation.Collections.IIterator> global::Windows.Foundation.Collections.IIterable>.First() => - new IEnumerator>.ToAbiHelper( - new KeyValuePair.Enumerator(_dictionary.GetEnumerator())); - - public V Lookup(K key) - { - V value; - bool keyFound = _dictionary.TryGetValue(key, out value); - - if (!keyFound) - { - Exception e = new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); - e.SetHResult(ExceptionHelpers.E_BOUNDS); - throw e; - } - - return value; - } - - public uint Size() => (uint)_dictionary.Count; - - public bool HasKey(K key) => _dictionary.ContainsKey(key); - - void global::Windows.Foundation.Collections.IMapView.Split(out global::Windows.Foundation.Collections.IMapView first, out global::Windows.Foundation.Collections.IMapView second) - { - if (_dictionary.Count < 2) - { - first = null; - second = null; - return; - } - - if (!(_dictionary is ConstantSplittableMap splittableMap)) - splittableMap = new ConstantSplittableMap(_dictionary); - - splittableMap.Split(out first, out second); - } - - private sealed class ConstantSplittableMap : global::Windows.Foundation.Collections.IMapView - { - private class KeyValuePairComparator : IComparer> - { - private static readonly IComparer keyComparator = Comparer.Default; - - public int Compare(global::System.Collections.Generic.KeyValuePair x, global::System.Collections.Generic.KeyValuePair y) - { - return keyComparator.Compare(x.Key, y.Key); - } - } - - private static readonly KeyValuePairComparator keyValuePairComparator = new KeyValuePairComparator(); - - private readonly global::System.Collections.Generic.KeyValuePair[] items; - private readonly int firstItemIndex; - private readonly int lastItemIndex; - - internal ConstantSplittableMap(global::System.Collections.Generic.IReadOnlyDictionary data) - { - if (data == null) - throw new ArgumentNullException(nameof(data)); - - firstItemIndex = 0; - lastItemIndex = data.Count - 1; - items = CreateKeyValueArray(data.Count, data.GetEnumerator()); - } - - private ConstantSplittableMap(global::System.Collections.Generic.KeyValuePair[] items, int firstItemIndex, int lastItemIndex) - { - this.items = items; - this.firstItemIndex = firstItemIndex; - this.lastItemIndex = lastItemIndex; - } - - private global::System.Collections.Generic.KeyValuePair[] CreateKeyValueArray(int count, global::System.Collections.Generic.IEnumerator> data) - { - global::System.Collections.Generic.KeyValuePair[] kvArray = new global::System.Collections.Generic.KeyValuePair[count]; - - int i = 0; - while (data.MoveNext()) - kvArray[i++] = data.Current; - - Array.Sort(kvArray, keyValuePairComparator); - - return kvArray; - } - - public int Count => lastItemIndex - firstItemIndex + 1; - - public uint Size => (uint)(lastItemIndex - firstItemIndex + 1); - - public V Lookup(K key) - { - V value; - bool found = TryGetValue(key, out value); - - if (!found) - { - Exception e = new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); - e.SetHResult(ExceptionHelpers.E_BOUNDS); - throw e; - } - - return value; - } - - public bool HasKey(K key) => - TryGetValue(key, out _); - - public global::Windows.Foundation.Collections.IIterator> First() => - new IEnumerator>.ToAbiHelper(GetEnumerator()); - - private global::System.Collections.Generic.IEnumerator> GetEnumerator() => - new Enumerator(items, firstItemIndex, lastItemIndex); - - public void Split(out global::Windows.Foundation.Collections.IMapView firstPartition, out global::Windows.Foundation.Collections.IMapView secondPartition) - { - if (Count < 2) - { - firstPartition = null; - secondPartition = null; - return; - } - - int pivot = (int)(((long)firstItemIndex + (long)lastItemIndex) / (long)2); - - firstPartition = new ConstantSplittableMap(items, firstItemIndex, pivot); - secondPartition = new ConstantSplittableMap(items, pivot + 1, lastItemIndex); - } - - public bool TryGetValue(K key, out V value) - { - var searchKey = new global::System.Collections.Generic.KeyValuePair(key, default!); - int index = Array.BinarySearch(items, firstItemIndex, Count, searchKey, keyValuePairComparator); - - if (index < 0) - { - value = default!; - return false; - } - - value = items[index].Value; - return true; - } - } - - internal struct Enumerator : global::System.Collections.Generic.IEnumerator> - { - private readonly global::System.Collections.Generic.KeyValuePair[] _array; - private readonly int _start; - private readonly int _end; - private int _current; - - internal Enumerator(global::System.Collections.Generic.KeyValuePair[] items, int first, int end) - { - _array = items; - _start = first; - _end = end; - _current = _start - 1; - } - - public bool MoveNext() - { - if (_current < _end) - { - _current++; - return true; - } - return false; - } - - public global::Windows.Foundation.Collections.IKeyValuePair Current - { - get - { - if (_current < _start) throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumNotStarted); - if (_current > _end) throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumEnded); - return new KeyValuePair.ToIKeyValuePair(ref _array[_current]); - } - } - - object IEnumerator.Current => Current; - - void IEnumerator.Reset() => - _current = _start - 1; - - public void Dispose() - { - } - } - } - - [Guid("E480CE40-A338-4ADA-ADCF-272272E48CB9")] - public struct Vftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - public global::System.Delegate Lookup_0; - internal _get_PropertyAsUInt32 get_Size_1; - public global::System.Delegate HasKey_2; - public IReadOnlyDictionary_Delegates.Split_3 Split_3; - public static Guid PIID = GuidGenerator.CreateIID(typeof(IReadOnlyDictionary)); - private static readonly Type Lookup_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, Marshaler.AbiType.MakeByRefType(), typeof(int) }); - private static readonly Type HasKey_2_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(byte).MakeByRefType(), typeof(int) }); - - internal unsafe Vftbl(IntPtr thisPtr) - { - var vftblPtr = Marshal.PtrToStructure(thisPtr); - var vftbl = (IntPtr*)vftblPtr.Vftbl; - IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); - Lookup_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], Lookup_0_Type); - get_Size_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsUInt32>(vftbl[7]); - HasKey_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8], HasKey_2_Type); - Split_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9]); - } - - private static readonly Vftbl AbiToProjectionVftable; - public static readonly IntPtr AbiToProjectionVftablePtr; - static unsafe Vftbl() - { - AbiToProjectionVftable = new Vftbl - { - IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, - Lookup_0 = global::System.Delegate.CreateDelegate(Lookup_0_Type, typeof(Vftbl).GetMethod("Do_Abi_Lookup_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType, Marshaler.AbiType)), - get_Size_1 = Do_Abi_get_Size_1, - HasKey_2 = global::System.Delegate.CreateDelegate(HasKey_2_Type, typeof(Vftbl).GetMethod("Do_Abi_HasKey_2", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), - Split_3 = Do_Abi_Split_3 - }; - var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 4); - Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); - nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Lookup_0); - nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Size_1); - nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.HasKey_2); - nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Split_3); - - AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; - } - - private static ConditionalWeakTable, ToAbiHelper> _adapterTable = - new ConditionalWeakTable, ToAbiHelper>(); - - private static global::Windows.Foundation.Collections.IMapView FindAdapter(IntPtr thisPtr) - { - var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); - return _adapterTable.GetValue(__this, (dictionary) => new ToAbiHelper(dictionary)); - } - - private static unsafe int Do_Abi_Lookup_0(void* thisPtr, KAbi key, out VAbi __return_value__) - { - V ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Lookup(Marshaler.FromAbi(key)); - __return_value__ = (VAbi)Marshaler.FromManaged(____return_value__); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_HasKey_2(void* thisPtr, KAbi key, out byte __return_value__) - { - bool ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(new IntPtr(thisPtr)).HasKey(Marshaler.FromAbi(key)); - __return_value__ = (byte)(____return_value__ ? 1 : 0); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_Split_3(IntPtr thisPtr, out IntPtr first, out IntPtr second) - { - - first = default; - second = default; - global::Windows.Foundation.Collections.IMapView __first = default; - global::Windows.Foundation.Collections.IMapView __second = default; - - try - { - FindAdapter(thisPtr).Split(out __first, out __second); - first = MarshalInterface>.FromManaged(__first); - second = MarshalInterface>.FromManaged(__second); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, out uint __return_value__) - { - uint ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(thisPtr).Size; - __return_value__ = ____return_value__; - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - } - public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) - { - if (thisPtr == IntPtr.Zero) - { - return null; - } - var vftblT = new Vftbl(thisPtr); - return ObjectReference.FromAbi(thisPtr, vftblT); - } - public static Guid PIID = Vftbl.PIID; - - public static implicit operator IReadOnlyDictionary(IObjectReference obj) => (obj != null) ? new IReadOnlyDictionary(obj) : null; - public static implicit operator IReadOnlyDictionary(ObjectReference obj) => (obj != null) ? new IReadOnlyDictionary(obj) : null; - protected readonly ObjectReference _obj; - public IObjectReference ObjRef { get => _obj; } - - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - public IReadOnlyDictionary(IObjectReference obj) : this(obj.As()) { } - public IReadOnlyDictionary(ObjectReference obj) - { - _obj = obj; - _FromMapView = new FromAbiHelper(this); - } - FromAbiHelper _FromMapView; - - public unsafe V Lookup(K key) - { - object __key = default; - var __params = new object[] { ThisPtr, null, null }; - try - { - __key = Marshaler.CreateMarshaler(key); - __params[1] = Marshaler.GetAbi(__key); - _obj.Vftbl.Lookup_0.DynamicInvokeAbi(__params); - return Marshaler.FromAbi(__params[2]); - } - finally - { - Marshaler.DisposeMarshaler(__key); - Marshaler.DisposeAbi(__params[2]); - } - } - - public unsafe bool HasKey(K key) - { - object __key = default; - var __params = new object[] { ThisPtr, null, null }; - try - { - __key = Marshaler.CreateMarshaler(key); - __params[1] = Marshaler.GetAbi(__key); - _obj.Vftbl.HasKey_2.DynamicInvokeAbi(__params); - return (byte)__params[2] != 0; - } - finally - { - Marshaler.DisposeMarshaler(__key); - } - } - - internal unsafe void Split(out global::Windows.Foundation.Collections.IMapView first, out global::Windows.Foundation.Collections.IMapView second) - { - IntPtr __first = default; - IntPtr __second = default; - try - { - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Split_3(ThisPtr, out __first, out __second)); - first = MarshalInterface>.FromAbi(__first); - second = MarshalInterface>.FromAbi(__second); - } - finally - { - MarshalInterface>.DisposeAbi(__first); - MarshalInterface>.DisposeAbi(__second); - } - } - - public unsafe uint Size - { - get - { - uint __retval = default; - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, out __retval)); - return __retval; - } - } - - public global::System.Collections.Generic.IEnumerable Keys => _FromMapView.Keys; - public global::System.Collections.Generic.IEnumerable Values => _FromMapView.Values; - public int Count => _FromMapView.Count; - public V this[K key] => _FromMapView[key]; - public bool ContainsKey(K key) => _FromMapView.ContainsKey(key); - public bool TryGetValue(K key, out V value) => _FromMapView.TryGetValue(key, out value); - public global::System.Collections.Generic.IEnumerator> GetEnumerator() => _FromMapView.GetEnumerator(); - IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - } - public static class IReadOnlyDictionary_Delegates - { - public unsafe delegate int Split_3(IntPtr thisPtr, out IntPtr first, out IntPtr second); - } -} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; +using System.Diagnostics; + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Windows.Foundation.Collections +{ + [Guid("E480CE40-A338-4ADA-ADCF-272272E48CB9")] + interface IMapView : IIterable> + { + V Lookup(K key); + bool HasKey(K key); + void Split(out IMapView first, out IMapView second); + uint Size { get; } + } +} + +namespace ABI.System.Collections.Generic +{ + using global::System; + using global::System.Runtime.CompilerServices; + + [Guid("E480CE40-A338-4ADA-ADCF-272272E48CB9")] + public 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))); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static global::System.Collections.Generic.IReadOnlyDictionary FromAbi(IntPtr thisPtr) => + thisPtr == IntPtr.Zero ? null : new IReadOnlyDictionary(ObjRefFromAbi(thisPtr)); + + public static IntPtr FromManaged(global::System.Collections.Generic.IReadOnlyDictionary value) => + (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); + + public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IReadOnlyDictionary)); + + public class FromAbiHelper : global::System.Collections.Generic.IReadOnlyDictionary + { + private readonly global::ABI.System.Collections.Generic.IReadOnlyDictionary _mapView; + private readonly global::ABI.System.Collections.Generic.IEnumerable> _enumerable; + + public FromAbiHelper(IObjectReference obj) : + this(new global::ABI.System.Collections.Generic.IReadOnlyDictionary(obj)) + { + } + + public FromAbiHelper(global::ABI.System.Collections.Generic.IReadOnlyDictionary mapView) + { + _mapView = mapView; + _enumerable = new ABI.System.Collections.Generic.IEnumerable>(mapView.ObjRef); + } + + public int Count + { + get + { + uint size = _mapView.Size; + + if (((uint)int.MaxValue) < size) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingDictionaryTooLarge); + } + + return (int)size; + } + } + + public V this[K key] { get => Indexer_Get(key); } + + private V Indexer_Get(K key) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + return Lookup(_mapView, key); + } + + public global::System.Collections.Generic.IEnumerable Keys + { + get => new ReadOnlyDictionaryKeyCollection(this); + } + + public global::System.Collections.Generic.IEnumerable Values + { + get => new ReadOnlyDictionaryValueCollection(this); + } + + public bool ContainsKey(K key) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + return _mapView.HasKey(key); + } + + public bool TryGetValue(K key, out V value) + { + if (key == null) + throw new ArgumentNullException(nameof(key)); + + // It may be faster to call HasKey then Lookup. On failure, we would otherwise + // throw an exception from Lookup. + if (!_mapView.HasKey(key)) + { + value = default!; + return false; + } + + try + { + value = _mapView.Lookup(key); + return true; + } + catch (Exception ex) // Still may hit this case due to a race condition + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + { + value = default!; + return false; + } + throw; + } + } + + private static V Lookup(global::ABI.System.Collections.Generic.IReadOnlyDictionary _this, K key) + { + try + { + return _this.Lookup(key); + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); + throw; + } + } + + public global::System.Collections.Generic.IEnumerator> GetEnumerator() => _enumerable.GetEnumerator(); + + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + + private sealed class ReadOnlyDictionaryKeyCollection : global::System.Collections.Generic.IEnumerable + { + private readonly global::System.Collections.Generic.IReadOnlyDictionary dictionary; + + public ReadOnlyDictionaryKeyCollection(global::System.Collections.Generic.IReadOnlyDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + } + + public global::System.Collections.Generic.IEnumerator GetEnumerator() + { + return new ReadOnlyDictionaryKeyEnumerator(dictionary); + } + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + + private sealed class ReadOnlyDictionaryKeyEnumerator : global::System.Collections.Generic.IEnumerator + { + private readonly global::System.Collections.Generic.IReadOnlyDictionary dictionary; + private global::System.Collections.Generic.IEnumerator> enumeration; + + public ReadOnlyDictionaryKeyEnumerator(global::System.Collections.Generic.IReadOnlyDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + enumeration = dictionary.GetEnumerator(); + } + + void IDisposable.Dispose() + { + enumeration.Dispose(); + } + + public bool MoveNext() + { + return enumeration.MoveNext(); + } + + object IEnumerator.Current => Current; + + public K Current => enumeration.Current.Key; + + public void Reset() + { + enumeration = dictionary.GetEnumerator(); + } + } + } + + private sealed class ReadOnlyDictionaryValueCollection : global::System.Collections.Generic.IEnumerable + { + private readonly global::System.Collections.Generic.IReadOnlyDictionary dictionary; + + public ReadOnlyDictionaryValueCollection(global::System.Collections.Generic.IReadOnlyDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + } + + public global::System.Collections.Generic.IEnumerator GetEnumerator() + { + return new ReadOnlyDictionaryValueEnumerator(dictionary); + } + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + + private sealed class ReadOnlyDictionaryValueEnumerator : global::System.Collections.Generic.IEnumerator + { + private readonly global::System.Collections.Generic.IReadOnlyDictionary dictionary; + private global::System.Collections.Generic.IEnumerator> enumeration; + + public ReadOnlyDictionaryValueEnumerator(global::System.Collections.Generic.IReadOnlyDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + this.dictionary = dictionary; + enumeration = dictionary.GetEnumerator(); + } + + void IDisposable.Dispose() + { + enumeration.Dispose(); + } + + public bool MoveNext() + { + return enumeration.MoveNext(); + } + + object IEnumerator.Current => Current; + + public V Current => enumeration.Current.Value; + + public void Reset() + { + enumeration = dictionary.GetEnumerator(); + } + } + } + } + + public class ToAbiHelper : global::Windows.Foundation.Collections.IMapView + { + private readonly global::System.Collections.Generic.IReadOnlyDictionary _dictionary; + + internal ToAbiHelper(global::System.Collections.Generic.IReadOnlyDictionary dictionary) => _dictionary = dictionary; + + uint global::Windows.Foundation.Collections.IMapView.Size { get => (uint)_dictionary.Count; } + + global::Windows.Foundation.Collections.IIterator> global::Windows.Foundation.Collections.IIterable>.First() => + new IEnumerator>.ToAbiHelper( + new KeyValuePair.Enumerator(_dictionary.GetEnumerator())); + + public V Lookup(K key) + { + V value; + bool keyFound = _dictionary.TryGetValue(key, out value); + + if (!keyFound) + { + Exception e = new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + + return value; + } + + public uint Size() => (uint)_dictionary.Count; + + public bool HasKey(K key) => _dictionary.ContainsKey(key); + + void global::Windows.Foundation.Collections.IMapView.Split(out global::Windows.Foundation.Collections.IMapView first, out global::Windows.Foundation.Collections.IMapView second) + { + if (_dictionary.Count < 2) + { + first = null; + second = null; + return; + } + + if (!(_dictionary is ConstantSplittableMap splittableMap)) + splittableMap = new ConstantSplittableMap(_dictionary); + + splittableMap.Split(out first, out second); + } + + private sealed class ConstantSplittableMap : global::Windows.Foundation.Collections.IMapView + { + private class KeyValuePairComparator : IComparer> + { + private static readonly IComparer keyComparator = Comparer.Default; + + public int Compare(global::System.Collections.Generic.KeyValuePair x, global::System.Collections.Generic.KeyValuePair y) + { + return keyComparator.Compare(x.Key, y.Key); + } + } + + private static readonly KeyValuePairComparator keyValuePairComparator = new KeyValuePairComparator(); + + private readonly global::System.Collections.Generic.KeyValuePair[] items; + private readonly int firstItemIndex; + private readonly int lastItemIndex; + + internal ConstantSplittableMap(global::System.Collections.Generic.IReadOnlyDictionary data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + + firstItemIndex = 0; + lastItemIndex = data.Count - 1; + items = CreateKeyValueArray(data.Count, data.GetEnumerator()); + } + + private ConstantSplittableMap(global::System.Collections.Generic.KeyValuePair[] items, int firstItemIndex, int lastItemIndex) + { + this.items = items; + this.firstItemIndex = firstItemIndex; + this.lastItemIndex = lastItemIndex; + } + + private global::System.Collections.Generic.KeyValuePair[] CreateKeyValueArray(int count, global::System.Collections.Generic.IEnumerator> data) + { + global::System.Collections.Generic.KeyValuePair[] kvArray = new global::System.Collections.Generic.KeyValuePair[count]; + + int i = 0; + while (data.MoveNext()) + kvArray[i++] = data.Current; + + Array.Sort(kvArray, keyValuePairComparator); + + return kvArray; + } + + public int Count => lastItemIndex - firstItemIndex + 1; + + public uint Size => (uint)(lastItemIndex - firstItemIndex + 1); + + public V Lookup(K key) + { + V value; + bool found = TryGetValue(key, out value); + + if (!found) + { + Exception e = new KeyNotFoundException(ErrorStrings.Format(ErrorStrings.Arg_KeyNotFoundWithKey, key.ToString())); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + + return value; + } + + public bool HasKey(K key) => + TryGetValue(key, out _); + + public global::Windows.Foundation.Collections.IIterator> First() => + new IEnumerator>.ToAbiHelper(GetEnumerator()); + + private global::System.Collections.Generic.IEnumerator> GetEnumerator() => + new Enumerator(items, firstItemIndex, lastItemIndex); + + public void Split(out global::Windows.Foundation.Collections.IMapView firstPartition, out global::Windows.Foundation.Collections.IMapView secondPartition) + { + if (Count < 2) + { + firstPartition = null; + secondPartition = null; + return; + } + + int pivot = (int)(((long)firstItemIndex + (long)lastItemIndex) / (long)2); + + firstPartition = new ConstantSplittableMap(items, firstItemIndex, pivot); + secondPartition = new ConstantSplittableMap(items, pivot + 1, lastItemIndex); + } + + public bool TryGetValue(K key, out V value) + { + var searchKey = new global::System.Collections.Generic.KeyValuePair(key, default!); + int index = Array.BinarySearch(items, firstItemIndex, Count, searchKey, keyValuePairComparator); + + if (index < 0) + { + value = default!; + return false; + } + + value = items[index].Value; + return true; + } + } + + internal struct Enumerator : global::System.Collections.Generic.IEnumerator> + { + private readonly global::System.Collections.Generic.KeyValuePair[] _array; + private readonly int _start; + private readonly int _end; + private int _current; + + internal Enumerator(global::System.Collections.Generic.KeyValuePair[] items, int first, int end) + { + _array = items; + _start = first; + _end = end; + _current = _start - 1; + } + + public bool MoveNext() + { + if (_current < _end) + { + _current++; + return true; + } + return false; + } + + public global::Windows.Foundation.Collections.IKeyValuePair Current + { + get + { + if (_current < _start) throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumNotStarted); + if (_current > _end) throw new InvalidOperationException(ErrorStrings.InvalidOperation_EnumEnded); + return new KeyValuePair.ToIKeyValuePair(ref _array[_current]); + } + } + + object IEnumerator.Current => Current; + + void IEnumerator.Reset() => + _current = _start - 1; + + public void Dispose() + { + } + } + } + + [Guid("E480CE40-A338-4ADA-ADCF-272272E48CB9")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate Lookup_0; + internal _get_PropertyAsUInt32 get_Size_1; + public global::System.Delegate HasKey_2; + public IReadOnlyDictionary_Delegates.Split_3 Split_3; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IReadOnlyDictionary)); + private static readonly Type Lookup_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, Marshaler.AbiType.MakeByRefType(), typeof(int) }); + private static readonly Type HasKey_2_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(byte).MakeByRefType(), typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + Lookup_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], Lookup_0_Type); + get_Size_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsUInt32>(vftbl[7]); + HasKey_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8], HasKey_2_Type); + Split_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9]); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + Lookup_0 = global::System.Delegate.CreateDelegate(Lookup_0_Type, typeof(Vftbl).GetMethod("Do_Abi_Lookup_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType, Marshaler.AbiType)), + get_Size_1 = Do_Abi_get_Size_1, + HasKey_2 = global::System.Delegate.CreateDelegate(HasKey_2_Type, typeof(Vftbl).GetMethod("Do_Abi_HasKey_2", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + Split_3 = Do_Abi_Split_3 + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 4); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Lookup_0); + nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Size_1); + nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.HasKey_2); + nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.Split_3); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable, ToAbiHelper> _adapterTable = + new ConditionalWeakTable, ToAbiHelper>(); + + private static global::Windows.Foundation.Collections.IMapView FindAdapter(IntPtr thisPtr) + { + var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); + return _adapterTable.GetValue(__this, (dictionary) => new ToAbiHelper(dictionary)); + } + + private static unsafe int Do_Abi_Lookup_0(void* thisPtr, KAbi key, out VAbi __return_value__) + { + V ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Lookup(Marshaler.FromAbi(key)); + __return_value__ = (VAbi)Marshaler.FromManaged(____return_value__); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_HasKey_2(void* thisPtr, KAbi key, out byte __return_value__) + { + bool ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).HasKey(Marshaler.FromAbi(key)); + __return_value__ = (byte)(____return_value__ ? 1 : 0); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_Split_3(IntPtr thisPtr, out IntPtr first, out IntPtr second) + { + + first = default; + second = default; + global::Windows.Foundation.Collections.IMapView __first = default; + global::Windows.Foundation.Collections.IMapView __second = default; + + try + { + FindAdapter(thisPtr).Split(out __first, out __second); + first = MarshalInterface>.FromManaged(__first); + second = MarshalInterface>.FromManaged(__second); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).Size; + __return_value__ = ____return_value__; + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + public static Guid PIID = Vftbl.PIID; + + public static implicit operator IReadOnlyDictionary(IObjectReference obj) => (obj != null) ? new IReadOnlyDictionary(obj) : null; + public static implicit operator IReadOnlyDictionary(ObjectReference obj) => (obj != null) ? new IReadOnlyDictionary(obj) : null; + protected readonly ObjectReference _obj; + public IObjectReference ObjRef { get => _obj; } + + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public IReadOnlyDictionary(IObjectReference obj) : this(obj.As()) { } + public IReadOnlyDictionary(ObjectReference obj) + { + _obj = obj; + _FromMapView = new FromAbiHelper(this); + } + FromAbiHelper _FromMapView; + + public unsafe V Lookup(K key) + { + object __key = default; + var __params = new object[] { ThisPtr, null, null }; + try + { + __key = Marshaler.CreateMarshaler(key); + __params[1] = Marshaler.GetAbi(__key); + _obj.Vftbl.Lookup_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[2]); + } + finally + { + Marshaler.DisposeMarshaler(__key); + Marshaler.DisposeAbi(__params[2]); + } + } + + public unsafe bool HasKey(K key) + { + object __key = default; + var __params = new object[] { ThisPtr, null, null }; + try + { + __key = Marshaler.CreateMarshaler(key); + __params[1] = Marshaler.GetAbi(__key); + _obj.Vftbl.HasKey_2.DynamicInvokeAbi(__params); + return (byte)__params[2] != 0; + } + finally + { + Marshaler.DisposeMarshaler(__key); + } + } + + internal unsafe void Split(out global::Windows.Foundation.Collections.IMapView first, out global::Windows.Foundation.Collections.IMapView second) + { + IntPtr __first = default; + IntPtr __second = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.Split_3(ThisPtr, out __first, out __second)); + first = MarshalInterface>.FromAbi(__first); + second = MarshalInterface>.FromAbi(__second); + } + finally + { + MarshalInterface>.DisposeAbi(__first); + MarshalInterface>.DisposeAbi(__second); + } + } + + public unsafe uint Size + { + get + { + uint __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, out __retval)); + return __retval; + } + } + + public global::System.Collections.Generic.IEnumerable Keys => _FromMapView.Keys; + public global::System.Collections.Generic.IEnumerable Values => _FromMapView.Values; + public int Count => _FromMapView.Count; + public V this[K key] => _FromMapView[key]; + public bool ContainsKey(K key) => _FromMapView.ContainsKey(key); + public bool TryGetValue(K key, out V value) => _FromMapView.TryGetValue(key, out value); + public global::System.Collections.Generic.IEnumerator> GetEnumerator() => _FromMapView.GetEnumerator(); + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + public static class IReadOnlyDictionary_Delegates + { + public unsafe delegate int Split_3(IntPtr thisPtr, out IntPtr first, out IntPtr second); + } +} diff --git a/WinRT.Runtime/Projections/IReadOnlyList.net5.cs b/WinRT.Runtime/Projections/IReadOnlyList.net5.cs new file mode 100644 index 000000000..5cc7bca5d --- /dev/null +++ b/WinRT.Runtime/Projections/IReadOnlyList.net5.cs @@ -0,0 +1,447 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; +using System.Diagnostics; + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Windows.Foundation.Collections +{ + [Guid("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56")] + interface IVectorView : IIterable + { + T GetAt(uint index); + bool IndexOf(T value, out uint index); + uint GetMany(uint startIndex, ref T[] items); + uint Size { get; } + } +} + +namespace ABI.System.Collections.Generic +{ + using global::System; + using global::System.Runtime.CompilerServices; + + [DynamicInterfaceCastableImplementation] + [Guid("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56")] + interface IReadOnlyList : global::System.Collections.Generic.IReadOnlyList, global::Windows.Foundation.Collections.IVectorView + { + public static IObjectReference CreateMarshaler(global::System.Collections.Generic.IReadOnlyList obj) => + obj is null ? null : ComWrappersSupport.CreateCCWForObject(obj).As(GuidGenerator.GetIID(typeof(IReadOnlyList))); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static IntPtr FromManaged(global::System.Collections.Generic.IReadOnlyList value) => + (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); + + public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IReadOnlyList)); + + public class FromAbiHelper : global::System.Collections.Generic.IReadOnlyList + { + private readonly global::Windows.Foundation.Collections.IVectorView _vectorView; + private readonly global::System.Collections.Generic.IEnumerable _enumerable; + + //public FromAbiHelper(IObjectReference obj) : + // this(new global::ABI.System.Collections.Generic.IReadOnlyList(obj)) + //{ + //} + + public FromAbiHelper(global::Windows.Foundation.Collections.IVectorView vectorView, ObjectReference objRef) + { + _vectorView = vectorView; + _enumerable = (global::System.Collections.Generic.IEnumerable)new IInspectable(objRef); + } + + public int Count + { + get + { + uint size = _vectorView.Size; + if (((uint)int.MaxValue) < size) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); + } + + return (int)size; + } + } + + public T this[int index] { get => Indexer_Get(index); } + + private T Indexer_Get(int index) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + + try + { + return _vectorView.GetAt((uint)index); + + // We delegate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + + throw; + } + } + + public global::System.Collections.Generic.IEnumerator GetEnumerator() => _enumerable.GetEnumerator(); + + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + + public sealed class ToAbiHelper : global::Windows.Foundation.Collections.IVectorView + { + private readonly global::System.Collections.Generic.IReadOnlyList _list; + + internal ToAbiHelper(global::System.Collections.Generic.IReadOnlyList list) => _list = list; + + global::Windows.Foundation.Collections.IIterator global::Windows.Foundation.Collections.IIterable.First() => + new IEnumerator.ToAbiHelper(_list.GetEnumerator()); + + private static void EnsureIndexInt32(uint index, int limit = int.MaxValue) + { + // We use '<=' and not '<' because int.MaxValue == index would imply + // that Size > int.MaxValue: + if (((uint)int.MaxValue) <= index || index >= (uint)limit) + { + Exception e = new ArgumentOutOfRangeException(nameof(index), ErrorStrings.ArgumentOutOfRange_IndexLargerThanMaxValue); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + } + + public T GetAt(uint index) + { + EnsureIndexInt32(index, _list.Count); + + try + { + return _list[(int)index]; + } + catch (ArgumentOutOfRangeException ex) + { + ex.SetHResult(ExceptionHelpers.E_BOUNDS); + throw; + } + } + + public uint Size => (uint)_list.Count; + + public bool IndexOf(T value, out uint index) + { + int ind = -1; + int max = _list.Count; + for (int i = 0; i < max; i++) + { + if (EqualityComparer.Default.Equals(value, _list[i])) + { + ind = i; + break; + } + } + + if (-1 == ind) + { + index = 0; + return false; + } + + index = (uint)ind; + return true; + } + + public uint GetMany(uint startIndex, ref T[] items) + { + // Spec says "calling GetMany with startIndex equal to the length of the vector + // (last valid index + 1) and any specified capacity will succeed and return zero actual + // elements". + if (startIndex == _list.Count) + return 0; + + EnsureIndexInt32(startIndex, _list.Count); + + if (items == null) + { + return 0; + } + + uint itemCount = Math.Min((uint)items.Length, (uint)_list.Count - startIndex); + + for (uint i = 0; i < itemCount; ++i) + { + items[i] = _list[(int)(i + startIndex)]; + } + + if (typeof(T) == typeof(string)) + { + string[] stringItems = (items as string[])!; + + // Fill in the rest of the array with string.Empty to avoid marshaling failure + for (uint i = itemCount; i < items.Length; ++i) + stringItems[i] = string.Empty; + } + + return itemCount; + } + } + + [Guid("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate GetAt_0; + internal _get_PropertyAsUInt32 get_Size_1; + public global::System.Delegate IndexOf_2; + public IReadOnlyList_Delegates.GetMany_3 GetMany_3; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IReadOnlyList)); + private static readonly Type GetAt_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), typeof(uint), Marshaler.AbiType.MakeByRefType(), typeof(int) }); + private static readonly Type IndexOf_2_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(uint).MakeByRefType(), typeof(byte).MakeByRefType(), typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + GetAt_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], GetAt_0_Type); + get_Size_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsUInt32>(vftbl[7]); + IndexOf_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8], IndexOf_2_Type); + GetMany_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9]); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + GetAt_0 = global::System.Delegate.CreateDelegate(GetAt_0_Type, typeof(Vftbl).GetMethod("Do_Abi_GetAt_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + get_Size_1 = Do_Abi_get_Size_1, + IndexOf_2 = global::System.Delegate.CreateDelegate(IndexOf_2_Type, typeof(Vftbl).GetMethod("Do_Abi_IndexOf_2", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + GetMany_3 = Do_Abi_GetMany_3 + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 4); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetAt_0); + nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Size_1); + nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.IndexOf_2); + nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetMany_3); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable, ToAbiHelper> _adapterTable = + new ConditionalWeakTable, ToAbiHelper>(); + + private static ToAbiHelper FindAdapter(IntPtr thisPtr) + { + var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); + return _adapterTable.GetValue(__this, (list) => new ToAbiHelper(list)); + } + + private static unsafe int Do_Abi_GetAt_0(void* thisPtr, uint index, out TAbi __return_value__) + { + T ____return_value__ = default; + __return_value__ = default; + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).GetAt(index); + __return_value__ = (TAbi)Marshaler.FromManaged(____return_value__); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_IndexOf_2(void* thisPtr, TAbi value, out uint index, out byte __return_value__) + { + bool ____return_value__ = default; + + index = default; + __return_value__ = default; + uint __index = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).IndexOf(Marshaler.FromAbi(value), out __index); + index = __index; + __return_value__ = (byte)(____return_value__ ? 1 : 0); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_GetMany_3(IntPtr thisPtr, uint startIndex, int __itemsSize, IntPtr items, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + T[] __items = Marshaler.FromAbiArray((__itemsSize, items)); + + try + { + ____return_value__ = FindAdapter(thisPtr).GetMany(startIndex, ref __items); + Marshaler.CopyManagedArray(__items, items); + __return_value__ = ____return_value__; + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).Size; + __return_value__ = ____return_value__; + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + public static Guid PIID = Vftbl.PIID; + + private static FromAbiHelper _FromVectorView(IWinRTObject _this) + { + var _obj = ((ObjectReference)_this.GetObjectReferenceForType(typeof(global::System.Collections.Generic.IReadOnlyList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + return (FromAbiHelper)_this.GetOrCreateTypeHelperData(typeof(global::System.Collections.Generic.IReadOnlyList).TypeHandle, + () => new FromAbiHelper((global::Windows.Foundation.Collections.IVectorView)_this, _obj)); + } + + unsafe T global::Windows.Foundation.Collections.IVectorView.GetAt(uint index) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IReadOnlyList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + var __params = new object[] { ThisPtr, index, null }; + try + { + _obj.Vftbl.GetAt_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[2]); + } + finally + { + Marshaler.DisposeAbi(__params[2]); + } + } + + unsafe bool global::Windows.Foundation.Collections.IVectorView.IndexOf(T value, out uint index) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IReadOnlyList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + object __value = default; + var __params = new object[] { ThisPtr, null, null, null }; + try + { + __value = Marshaler.CreateMarshaler(value); + __params[1] = Marshaler.GetAbi(__value); + _obj.Vftbl.IndexOf_2.DynamicInvokeAbi(__params); + index = (uint)__params[2]; + return (byte)__params[3] != 0; + } + finally + { + Marshaler.DisposeMarshaler(__value); + } + } + + unsafe uint global::Windows.Foundation.Collections.IVectorView.GetMany(uint startIndex, ref T[] items) + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IReadOnlyList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + object __items = default; + int __items_length = default; + IntPtr __items_data = default; + uint __retval = default; + try + { + __items = Marshaler.CreateMarshalerArray(items); + (__items_length, __items_data) = Marshaler.GetAbiArray(__items); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetMany_3(ThisPtr, startIndex, __items_length, __items_data, out __retval)); + items = Marshaler.FromAbiArray((__items_length, __items_data)); + return __retval; + } + finally + { + Marshaler.DisposeMarshalerArray(__items); + } + } + + unsafe uint global::Windows.Foundation.Collections.IVectorView.Size + { + get + { + var _obj = ((ObjectReference)((IWinRTObject)this).GetObjectReferenceForType(typeof(global::System.Collections.Generic.IReadOnlyList).TypeHandle)); + var ThisPtr = _obj.ThisPtr; + + uint __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, out __retval)); + return __retval; + } + } + + int global::System.Collections.Generic.IReadOnlyCollection.Count => _FromVectorView((IWinRTObject)this).Count; + + T global::System.Collections.Generic.IReadOnlyList.this[int index] => _FromVectorView((IWinRTObject)this)[index]; + + global::System.Collections.Generic.IEnumerator global::System.Collections.Generic.IEnumerable.GetEnumerator() => _FromVectorView((IWinRTObject)this).GetEnumerator(); + + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + + public 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/WinRT.Runtime/Projections/IReadOnlyList.cs b/WinRT.Runtime/Projections/IReadOnlyList.netstandard2.0.cs similarity index 97% rename from WinRT.Runtime/Projections/IReadOnlyList.cs rename to WinRT.Runtime/Projections/IReadOnlyList.netstandard2.0.cs index 9d21b939b..e4c93f3b6 100644 --- a/WinRT.Runtime/Projections/IReadOnlyList.cs +++ b/WinRT.Runtime/Projections/IReadOnlyList.netstandard2.0.cs @@ -1,443 +1,443 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.InteropServices; -using WinRT; -using WinRT.Interop; -using System.Diagnostics; - -#pragma warning disable 0169 // warning CS0169: The field '...' is never used -#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to - -namespace Windows.Foundation.Collections -{ - [Guid("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56")] - interface IVectorView : IIterable - { - T GetAt(uint index); - bool IndexOf(T value, out uint index); - uint GetMany(uint startIndex, ref T[] items); - uint Size { get; } - } -} - -namespace ABI.System.Collections.Generic -{ - using global::System; - using global::System.Runtime.CompilerServices; - - [Guid("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56")] - public 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))); - - public static IntPtr GetAbi(IObjectReference objRef) => - objRef?.ThisPtr ?? IntPtr.Zero; - - public static global::System.Collections.Generic.IReadOnlyList FromAbi(IntPtr thisPtr) => - thisPtr == IntPtr.Zero ? null : new IReadOnlyList(ObjRefFromAbi(thisPtr)); - - public static IntPtr FromManaged(global::System.Collections.Generic.IReadOnlyList value) => - (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); - - public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); - - public static void DisposeAbi(IntPtr abi) => - MarshalInterfaceHelper>.DisposeAbi(abi); - - public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IReadOnlyList)); - - public class FromAbiHelper : global::System.Collections.Generic.IReadOnlyList - { - private readonly global::ABI.System.Collections.Generic.IReadOnlyList _vectorView; - private readonly global::ABI.System.Collections.Generic.IEnumerable _enumerable; - - public FromAbiHelper(IObjectReference obj) : - this(new global::ABI.System.Collections.Generic.IReadOnlyList(obj)) - { - } - - public FromAbiHelper(global::ABI.System.Collections.Generic.IReadOnlyList vectorView) - { - _vectorView = vectorView; - _enumerable = new ABI.System.Collections.Generic.IEnumerable(vectorView.ObjRef); - } - - public int Count - { - get - { - uint size = _vectorView.Size; - if (((uint)int.MaxValue) < size) - { - throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); - } - - return (int)size; - } - } - - public T this[int index] { get => Indexer_Get(index); } - - private T Indexer_Get(int index) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - - try - { - return _vectorView.GetAt((uint)index); - - // We delegate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (ExceptionHelpers.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - - public global::System.Collections.Generic.IEnumerator GetEnumerator() => _enumerable.GetEnumerator(); - - global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - } - - public sealed class ToAbiHelper : global::Windows.Foundation.Collections.IVectorView - { - private readonly global::System.Collections.Generic.IReadOnlyList _list; - - internal ToAbiHelper(global::System.Collections.Generic.IReadOnlyList list) => _list = list; - - global::Windows.Foundation.Collections.IIterator global::Windows.Foundation.Collections.IIterable.First() => - new IEnumerator.ToAbiHelper(_list.GetEnumerator()); - - private static void EnsureIndexInt32(uint index, int limit = int.MaxValue) - { - // We use '<=' and not '<' because int.MaxValue == index would imply - // that Size > int.MaxValue: - if (((uint)int.MaxValue) <= index || index >= (uint)limit) - { - Exception e = new ArgumentOutOfRangeException(nameof(index), ErrorStrings.ArgumentOutOfRange_IndexLargerThanMaxValue); - e.SetHResult(ExceptionHelpers.E_BOUNDS); - throw e; - } - } - - public T GetAt(uint index) - { - EnsureIndexInt32(index, _list.Count); - - try - { - return _list[(int)index]; - } - catch (ArgumentOutOfRangeException ex) - { - ex.SetHResult(ExceptionHelpers.E_BOUNDS); - throw; - } - } - - public uint Size => (uint)_list.Count; - - public bool IndexOf(T value, out uint index) - { - int ind = -1; - int max = _list.Count; - for (int i = 0; i < max; i++) - { - if (EqualityComparer.Default.Equals(value, _list[i])) - { - ind = i; - break; - } - } - - if (-1 == ind) - { - index = 0; - return false; - } - - index = (uint)ind; - return true; - } - - public uint GetMany(uint startIndex, ref T[] items) - { - // Spec says "calling GetMany with startIndex equal to the length of the vector - // (last valid index + 1) and any specified capacity will succeed and return zero actual - // elements". - if (startIndex == _list.Count) - return 0; - - EnsureIndexInt32(startIndex, _list.Count); - - if (items == null) - { - return 0; - } - - uint itemCount = Math.Min((uint)items.Length, (uint)_list.Count - startIndex); - - for (uint i = 0; i < itemCount; ++i) - { - items[i] = _list[(int)(i + startIndex)]; - } - - if (typeof(T) == typeof(string)) - { - string[] stringItems = (items as string[])!; - - // Fill in the rest of the array with string.Empty to avoid marshaling failure - for (uint i = itemCount; i < items.Length; ++i) - stringItems[i] = string.Empty; - } - - return itemCount; - } - } - - [Guid("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56")] - public struct Vftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - public global::System.Delegate GetAt_0; - internal _get_PropertyAsUInt32 get_Size_1; - public global::System.Delegate IndexOf_2; - public IReadOnlyList_Delegates.GetMany_3 GetMany_3; - public static Guid PIID = GuidGenerator.CreateIID(typeof(IReadOnlyList)); - private static readonly Type GetAt_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), typeof(uint), Marshaler.AbiType.MakeByRefType(), typeof(int) }); - private static readonly Type IndexOf_2_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(uint).MakeByRefType(), typeof(byte).MakeByRefType(), typeof(int) }); - - internal unsafe Vftbl(IntPtr thisPtr) - { - var vftblPtr = Marshal.PtrToStructure(thisPtr); - var vftbl = (IntPtr*)vftblPtr.Vftbl; - IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); - GetAt_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], GetAt_0_Type); - get_Size_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsUInt32>(vftbl[7]); - IndexOf_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8], IndexOf_2_Type); - GetMany_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9]); - } - - private static readonly Vftbl AbiToProjectionVftable; - public static readonly IntPtr AbiToProjectionVftablePtr; - static unsafe Vftbl() - { - AbiToProjectionVftable = new Vftbl - { - IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, - GetAt_0 = global::System.Delegate.CreateDelegate(GetAt_0_Type, typeof(Vftbl).GetMethod("Do_Abi_GetAt_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), - get_Size_1 = Do_Abi_get_Size_1, - IndexOf_2 = global::System.Delegate.CreateDelegate(IndexOf_2_Type, typeof(Vftbl).GetMethod("Do_Abi_IndexOf_2", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), - GetMany_3 = Do_Abi_GetMany_3 - }; - var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 4); - Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); - nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetAt_0); - nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Size_1); - nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.IndexOf_2); - nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetMany_3); - - AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; - } - - private static ConditionalWeakTable, ToAbiHelper> _adapterTable = - new ConditionalWeakTable, ToAbiHelper>(); - - private static ToAbiHelper FindAdapter(IntPtr thisPtr) - { - var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); - return _adapterTable.GetValue(__this, (list) => new ToAbiHelper(list)); - } - - private static unsafe int Do_Abi_GetAt_0(void* thisPtr, uint index, out TAbi __return_value__) - { - T ____return_value__ = default; - __return_value__ = default; - try - { - ____return_value__ = FindAdapter(new IntPtr(thisPtr)).GetAt(index); - __return_value__ = (TAbi)Marshaler.FromManaged(____return_value__); - - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_IndexOf_2(void* thisPtr, TAbi value, out uint index, out byte __return_value__) - { - bool ____return_value__ = default; - - index = default; - __return_value__ = default; - uint __index = default; - - try - { - ____return_value__ = FindAdapter(new IntPtr(thisPtr)).IndexOf(Marshaler.FromAbi(value), out __index); - index = __index; - __return_value__ = (byte)(____return_value__ ? 1 : 0); - - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_GetMany_3(IntPtr thisPtr, uint startIndex, int __itemsSize, IntPtr items, out uint __return_value__) - { - uint ____return_value__ = default; - - __return_value__ = default; - T[] __items = Marshaler.FromAbiArray((__itemsSize, items)); - - try - { - ____return_value__ = FindAdapter(thisPtr).GetMany(startIndex, ref __items); - Marshaler.CopyManagedArray(__items, items); - __return_value__ = ____return_value__; - - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, out uint __return_value__) - { - uint ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = FindAdapter(thisPtr).Size; - __return_value__ = ____return_value__; - - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - } - public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) - { - if (thisPtr == IntPtr.Zero) - { - return null; - } - var vftblT = new Vftbl(thisPtr); - return ObjectReference.FromAbi(thisPtr, vftblT); - } - public static Guid PIID = Vftbl.PIID; - - public static implicit operator IReadOnlyList(IObjectReference obj) => (obj != null) ? new IReadOnlyList(obj) : null; - public static implicit operator IReadOnlyList(ObjectReference obj) => (obj != null) ? new IReadOnlyList(obj) : null; - protected readonly ObjectReference _obj; - public IObjectReference ObjRef { get => _obj; } - - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - public IReadOnlyList(IObjectReference obj) : this(obj.As()) { } - public IReadOnlyList(ObjectReference obj) - { - _obj = obj; - _FromVectorView = new FromAbiHelper(this); - } - FromAbiHelper _FromVectorView; - - public unsafe T GetAt(uint index) - { - var __params = new object[] { ThisPtr, index, null }; - try - { - _obj.Vftbl.GetAt_0.DynamicInvokeAbi(__params); - return Marshaler.FromAbi(__params[2]); - } - finally - { - Marshaler.DisposeAbi(__params[2]); - } - } - - public unsafe bool IndexOf(T value, out uint index) - { - object __value = default; - var __params = new object[] { ThisPtr, null, null, null }; - try - { - __value = Marshaler.CreateMarshaler(value); - __params[1] = Marshaler.GetAbi(__value); - _obj.Vftbl.IndexOf_2.DynamicInvokeAbi(__params); - index = (uint)__params[2]; - return (byte)__params[3] != 0; - } - finally - { - Marshaler.DisposeMarshaler(__value); - } - } - - public unsafe uint GetMany(uint startIndex, ref T[] items) - { - object __items = default; - int __items_length = default; - IntPtr __items_data = default; - uint __retval = default; - try - { - __items = Marshaler.CreateMarshalerArray(items); - (__items_length, __items_data) = Marshaler.GetAbiArray(__items); - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetMany_3(ThisPtr, startIndex, __items_length, __items_data, out __retval)); - items = Marshaler.FromAbiArray((__items_length, __items_data)); - return __retval; - } - finally - { - Marshaler.DisposeMarshalerArray(__items); - } - } - - public unsafe uint Size - { - get - { - uint __retval = default; - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, out __retval)); - return __retval; - } - } - - public int Count => _FromVectorView.Count; - - public T this[int index] => _FromVectorView[index]; - - public global::System.Collections.Generic.IEnumerator GetEnumerator() => _FromVectorView.GetEnumerator(); - - IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - } - public static class IReadOnlyList_Delegates - { - public unsafe delegate int GetMany_3(IntPtr thisPtr, uint startIndex, int __itemsSize, IntPtr items, out uint __return_value__); - } -} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; +using System.Diagnostics; + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Windows.Foundation.Collections +{ + [Guid("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56")] + interface IVectorView : IIterable + { + T GetAt(uint index); + bool IndexOf(T value, out uint index); + uint GetMany(uint startIndex, ref T[] items); + uint Size { get; } + } +} + +namespace ABI.System.Collections.Generic +{ + using global::System; + using global::System.Runtime.CompilerServices; + + [Guid("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56")] + public 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))); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static global::System.Collections.Generic.IReadOnlyList FromAbi(IntPtr thisPtr) => + thisPtr == IntPtr.Zero ? null : new IReadOnlyList(ObjRefFromAbi(thisPtr)); + + public static IntPtr FromManaged(global::System.Collections.Generic.IReadOnlyList value) => + (value is null) ? IntPtr.Zero : CreateMarshaler(value).GetRef(); + + public static void DisposeMarshaler(IObjectReference objRef) => objRef?.Dispose(); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IReadOnlyList)); + + public class FromAbiHelper : global::System.Collections.Generic.IReadOnlyList + { + private readonly global::ABI.System.Collections.Generic.IReadOnlyList _vectorView; + private readonly global::ABI.System.Collections.Generic.IEnumerable _enumerable; + + public FromAbiHelper(IObjectReference obj) : + this(new global::ABI.System.Collections.Generic.IReadOnlyList(obj)) + { + } + + public FromAbiHelper(global::ABI.System.Collections.Generic.IReadOnlyList vectorView) + { + _vectorView = vectorView; + _enumerable = new ABI.System.Collections.Generic.IEnumerable(vectorView.ObjRef); + } + + public int Count + { + get + { + uint size = _vectorView.Size; + if (((uint)int.MaxValue) < size) + { + throw new InvalidOperationException(ErrorStrings.InvalidOperation_CollectionBackingListTooLarge); + } + + return (int)size; + } + } + + public T this[int index] { get => Indexer_Get(index); } + + private T Indexer_Get(int index) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index)); + + try + { + return _vectorView.GetAt((uint)index); + + // We delegate bounds checking to the underlying collection and if it detected a fault, + // we translate it to the right exception: + } + catch (Exception ex) + { + if (ExceptionHelpers.E_BOUNDS == ex.HResult) + throw new ArgumentOutOfRangeException(nameof(index)); + + throw; + } + } + + public global::System.Collections.Generic.IEnumerator GetEnumerator() => _enumerable.GetEnumerator(); + + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + + public sealed class ToAbiHelper : global::Windows.Foundation.Collections.IVectorView + { + private readonly global::System.Collections.Generic.IReadOnlyList _list; + + internal ToAbiHelper(global::System.Collections.Generic.IReadOnlyList list) => _list = list; + + global::Windows.Foundation.Collections.IIterator global::Windows.Foundation.Collections.IIterable.First() => + new IEnumerator.ToAbiHelper(_list.GetEnumerator()); + + private static void EnsureIndexInt32(uint index, int limit = int.MaxValue) + { + // We use '<=' and not '<' because int.MaxValue == index would imply + // that Size > int.MaxValue: + if (((uint)int.MaxValue) <= index || index >= (uint)limit) + { + Exception e = new ArgumentOutOfRangeException(nameof(index), ErrorStrings.ArgumentOutOfRange_IndexLargerThanMaxValue); + e.SetHResult(ExceptionHelpers.E_BOUNDS); + throw e; + } + } + + public T GetAt(uint index) + { + EnsureIndexInt32(index, _list.Count); + + try + { + return _list[(int)index]; + } + catch (ArgumentOutOfRangeException ex) + { + ex.SetHResult(ExceptionHelpers.E_BOUNDS); + throw; + } + } + + public uint Size => (uint)_list.Count; + + public bool IndexOf(T value, out uint index) + { + int ind = -1; + int max = _list.Count; + for (int i = 0; i < max; i++) + { + if (EqualityComparer.Default.Equals(value, _list[i])) + { + ind = i; + break; + } + } + + if (-1 == ind) + { + index = 0; + return false; + } + + index = (uint)ind; + return true; + } + + public uint GetMany(uint startIndex, ref T[] items) + { + // Spec says "calling GetMany with startIndex equal to the length of the vector + // (last valid index + 1) and any specified capacity will succeed and return zero actual + // elements". + if (startIndex == _list.Count) + return 0; + + EnsureIndexInt32(startIndex, _list.Count); + + if (items == null) + { + return 0; + } + + uint itemCount = Math.Min((uint)items.Length, (uint)_list.Count - startIndex); + + for (uint i = 0; i < itemCount; ++i) + { + items[i] = _list[(int)(i + startIndex)]; + } + + if (typeof(T) == typeof(string)) + { + string[] stringItems = (items as string[])!; + + // Fill in the rest of the array with string.Empty to avoid marshaling failure + for (uint i = itemCount; i < items.Length; ++i) + stringItems[i] = string.Empty; + } + + return itemCount; + } + } + + [Guid("BBE1FA4C-B0E3-4583-BAEF-1F1B2E483E56")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate GetAt_0; + internal _get_PropertyAsUInt32 get_Size_1; + public global::System.Delegate IndexOf_2; + public IReadOnlyList_Delegates.GetMany_3 GetMany_3; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IReadOnlyList)); + private static readonly Type GetAt_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), typeof(uint), Marshaler.AbiType.MakeByRefType(), typeof(int) }); + private static readonly Type IndexOf_2_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType, typeof(uint).MakeByRefType(), typeof(byte).MakeByRefType(), typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + GetAt_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], GetAt_0_Type); + get_Size_1 = Marshal.GetDelegateForFunctionPointer<_get_PropertyAsUInt32>(vftbl[7]); + IndexOf_2 = Marshal.GetDelegateForFunctionPointer(vftbl[8], IndexOf_2_Type); + GetMany_3 = Marshal.GetDelegateForFunctionPointer(vftbl[9]); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + GetAt_0 = global::System.Delegate.CreateDelegate(GetAt_0_Type, typeof(Vftbl).GetMethod("Do_Abi_GetAt_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + get_Size_1 = Do_Abi_get_Size_1, + IndexOf_2 = global::System.Delegate.CreateDelegate(IndexOf_2_Type, typeof(Vftbl).GetMethod("Do_Abi_IndexOf_2", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + GetMany_3 = Do_Abi_GetMany_3 + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 4); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetAt_0); + nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Size_1); + nativeVftbl[8] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.IndexOf_2); + nativeVftbl[9] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.GetMany_3); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable, ToAbiHelper> _adapterTable = + new ConditionalWeakTable, ToAbiHelper>(); + + private static ToAbiHelper FindAdapter(IntPtr thisPtr) + { + var __this = global::WinRT.ComWrappersSupport.FindObject>(thisPtr); + return _adapterTable.GetValue(__this, (list) => new ToAbiHelper(list)); + } + + private static unsafe int Do_Abi_GetAt_0(void* thisPtr, uint index, out TAbi __return_value__) + { + T ____return_value__ = default; + __return_value__ = default; + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).GetAt(index); + __return_value__ = (TAbi)Marshaler.FromManaged(____return_value__); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_IndexOf_2(void* thisPtr, TAbi value, out uint index, out byte __return_value__) + { + bool ____return_value__ = default; + + index = default; + __return_value__ = default; + uint __index = default; + + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).IndexOf(Marshaler.FromAbi(value), out __index); + index = __index; + __return_value__ = (byte)(____return_value__ ? 1 : 0); + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_GetMany_3(IntPtr thisPtr, uint startIndex, int __itemsSize, IntPtr items, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + T[] __items = Marshaler.FromAbiArray((__itemsSize, items)); + + try + { + ____return_value__ = FindAdapter(thisPtr).GetMany(startIndex, ref __items); + Marshaler.CopyManagedArray(__items, items); + __return_value__ = ____return_value__; + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_get_Size_1(IntPtr thisPtr, out uint __return_value__) + { + uint ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = FindAdapter(thisPtr).Size; + __return_value__ = ____return_value__; + + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + public static ObjectReference ObjRefFromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + public static Guid PIID = Vftbl.PIID; + + public static implicit operator IReadOnlyList(IObjectReference obj) => (obj != null) ? new IReadOnlyList(obj) : null; + public static implicit operator IReadOnlyList(ObjectReference obj) => (obj != null) ? new IReadOnlyList(obj) : null; + protected readonly ObjectReference _obj; + public IObjectReference ObjRef { get => _obj; } + + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public IReadOnlyList(IObjectReference obj) : this(obj.As()) { } + public IReadOnlyList(ObjectReference obj) + { + _obj = obj; + _FromVectorView = new FromAbiHelper(this); + } + FromAbiHelper _FromVectorView; + + public unsafe T GetAt(uint index) + { + var __params = new object[] { ThisPtr, index, null }; + try + { + _obj.Vftbl.GetAt_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[2]); + } + finally + { + Marshaler.DisposeAbi(__params[2]); + } + } + + public unsafe bool IndexOf(T value, out uint index) + { + object __value = default; + var __params = new object[] { ThisPtr, null, null, null }; + try + { + __value = Marshaler.CreateMarshaler(value); + __params[1] = Marshaler.GetAbi(__value); + _obj.Vftbl.IndexOf_2.DynamicInvokeAbi(__params); + index = (uint)__params[2]; + return (byte)__params[3] != 0; + } + finally + { + Marshaler.DisposeMarshaler(__value); + } + } + + public unsafe uint GetMany(uint startIndex, ref T[] items) + { + object __items = default; + int __items_length = default; + IntPtr __items_data = default; + uint __retval = default; + try + { + __items = Marshaler.CreateMarshalerArray(items); + (__items_length, __items_data) = Marshaler.GetAbiArray(__items); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetMany_3(ThisPtr, startIndex, __items_length, __items_data, out __retval)); + items = Marshaler.FromAbiArray((__items_length, __items_data)); + return __retval; + } + finally + { + Marshaler.DisposeMarshalerArray(__items); + } + } + + public unsafe uint Size + { + get + { + uint __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Size_1(ThisPtr, out __retval)); + return __retval; + } + } + + public int Count => _FromVectorView.Count; + + public T this[int index] => _FromVectorView[index]; + + public global::System.Collections.Generic.IEnumerator GetEnumerator() => _FromVectorView.GetEnumerator(); + + IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + public 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/WinRT.Runtime/Projections/IReferenceArray.net5.cs b/WinRT.Runtime/Projections/IReferenceArray.net5.cs new file mode 100644 index 000000000..ccddfd163 --- /dev/null +++ b/WinRT.Runtime/Projections/IReferenceArray.net5.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using WinRT; +using WinRT.Interop; + +namespace Windows.Foundation +{ + // Provide a stub definition of IReferenceArray so we have + // a "public" type for the type mapping definition. + // IReferenceArray cannot appear in signatures, so it doesn't need to actually be public. + [Guid("61C17707-2D65-11E0-9AE8-D48564015472")] + internal interface IReferenceArray + { + T[] Value { get; } + } +} + +namespace ABI.Windows.Foundation +{ + internal static class BoxedArrayIReferenceArrayImpl + { + private static readonly IReferenceArray.Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe BoxedArrayIReferenceArrayImpl() + { + AbiToProjectionVftable = new IReferenceArray.Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + get_Value_0 = Do_Abi_get_Value_0 + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(BoxedArrayIReferenceArrayImpl), Marshal.SizeOf() + sizeof(IntPtr) * 1); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Value_0); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static unsafe int Do_Abi_get_Value_0(IntPtr thisPtr, out int ____return_value__Size, out IntPtr __return_value__) + { + T[] ____return_value__ = default; + + __return_value__ = default; + ____return_value__Size = default; + + try + { + ____return_value__ = (T[])global::WinRT.ComWrappersSupport.FindObject(thisPtr); + (____return_value__Size, __return_value__) = Marshaler.FromManagedArray(____return_value__); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + + [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] + [Guid("61C17707-2D65-11E0-9AE8-D48564015472")] + internal class IReferenceArray : global::Windows.Foundation.IReferenceArray + { + public static IObjectReference CreateMarshaler(object value) + { + if (value is null) + { + return null; + } + return ComWrappersSupport.CreateCCWForObject(value).As(PIID); + } + + public static IntPtr GetAbi(IObjectReference m) => m?.ThisPtr ?? IntPtr.Zero; + + public static object FromAbi(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(ptr); + var wrapper = new IReferenceArray(ObjectReference.FromAbi(ptr, vftblT)); + return wrapper.Value; + } + + public static unsafe void CopyManaged(object o, IntPtr dest) + { + using var objRef = CreateMarshaler(o); + *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero; + } + + public static IntPtr FromManaged(object value) + { + if (value is null) + { + return IntPtr.Zero; + } + return CreateMarshaler(value).GetRef(); + } + + public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } + public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(IReferenceArray)); + + [Guid("61C17707-2D65-11E0-9AE8-D48564015472")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public IReferenceArray_Delegates.get_Value_0 get_Value_0; + public static Guid PIID = GuidGenerator.CreateIID(typeof(IReferenceArray)); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + get_Value_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6]); + } + } + + public static Guid PIID = Vftbl.PIID; + + public static implicit operator IReferenceArray(IObjectReference obj) => (obj != null) ? new IReferenceArray(obj) : null; + public static implicit operator IReferenceArray(ObjectReference obj) => (obj != null) ? new IReferenceArray(obj) : null; + protected readonly ObjectReference _obj; + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public IReferenceArray(IObjectReference obj) : this(obj.As()) { } + public IReferenceArray(ObjectReference obj) + { + _obj = obj; + } + + + public unsafe T[] Value + { + get + { + int __retval_length = default; + IntPtr __retval_data = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Value_0(ThisPtr, out __retval_length, out __retval_data)); + return Marshaler.FromAbiArray((__retval_length, __retval_data)); + } + finally + { + Marshaler.DisposeAbiArray((__retval_length, __retval_data)); + } + } + } + } + + internal static class IReferenceArray_Delegates + { + public unsafe delegate int get_Value_0(IntPtr thisPtr, out int ____return_value__Size, out IntPtr __return_value__); + } +} \ No newline at end of file diff --git a/WinRT.Runtime/Projections/IReferenceArray.cs b/WinRT.Runtime/Projections/IReferenceArray.netstandard2.0.cs similarity index 99% rename from WinRT.Runtime/Projections/IReferenceArray.cs rename to WinRT.Runtime/Projections/IReferenceArray.netstandard2.0.cs index d7b4130dc..710e3f6f0 100644 --- a/WinRT.Runtime/Projections/IReferenceArray.cs +++ b/WinRT.Runtime/Projections/IReferenceArray.netstandard2.0.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; diff --git a/WinRT.Runtime/Projections/IStringable.net5.cs b/WinRT.Runtime/Projections/IStringable.net5.cs new file mode 100644 index 000000000..5817a1cf4 --- /dev/null +++ b/WinRT.Runtime/Projections/IStringable.net5.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Runtime.InteropServices; +using WinRT; + +namespace ABI.Windows.Foundation +{ + [Guid("96369F54-8EB6-48F0-ABCE-C1B211E627C3")] + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct ManagedIStringableVftbl + { + + internal IInspectable.Vftbl IInspectableVftbl; + private void* _ToString_0; + private delegate* stdcall ToString_0 { get => (delegate* stdcall)_ToString_0; set => _ToString_0 = value; } + + private static readonly ManagedIStringableVftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + + static unsafe ManagedIStringableVftbl() + { + AbiToProjectionVftable = new ManagedIStringableVftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + + _ToString_0 = (delegate*)&Do_Abi_ToString_0 + + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(ManagedIStringableVftbl), Marshal.SizeOf() + sizeof(IntPtr) * 1); + Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + + [UnmanagedCallersOnly] + + private static unsafe int Do_Abi_ToString_0(IntPtr thisPtr, IntPtr* value) + { + try + { + string __value = global::WinRT.ComWrappersSupport.FindObject(thisPtr).ToString(); + *value = MarshalString.FromManaged(__value); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } +} diff --git a/WinRT.Runtime/Projections/IStringable.cs b/WinRT.Runtime/Projections/IStringable.netstandard2.0.cs similarity index 90% rename from WinRT.Runtime/Projections/IStringable.cs rename to WinRT.Runtime/Projections/IStringable.netstandard2.0.cs index 072cbdb26..3c1a805d1 100644 --- a/WinRT.Runtime/Projections/IStringable.cs +++ b/WinRT.Runtime/Projections/IStringable.netstandard2.0.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; @@ -18,29 +18,25 @@ internal unsafe struct ManagedIStringableVftbl private static readonly ManagedIStringableVftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 + private unsafe delegate int ToStringDelegate(IntPtr thisPtr, IntPtr* value); private static readonly ToStringDelegate delegateCache; -#endif + static unsafe ManagedIStringableVftbl() { AbiToProjectionVftable = new ManagedIStringableVftbl { IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, -#if NETSTANDARD2_0 + _ToString_0 = Marshal.GetFunctionPointerForDelegate(delegateCache = Do_Abi_ToString_0).ToPointer() -#else - _ToString_0 = (delegate*)&Do_Abi_ToString_0 -#endif + }; var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(ManagedIStringableVftbl), Marshal.SizeOf() + sizeof(IntPtr) * 1); Marshal.StructureToPtr(AbiToProjectionVftable, (IntPtr)nativeVftbl, false); AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif + private static unsafe int Do_Abi_ToString_0(IntPtr thisPtr, IntPtr* value) { try diff --git a/WinRT.Runtime/Projections/KeyValuePair.net5.cs b/WinRT.Runtime/Projections/KeyValuePair.net5.cs new file mode 100644 index 000000000..d917c1590 --- /dev/null +++ b/WinRT.Runtime/Projections/KeyValuePair.net5.cs @@ -0,0 +1,243 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; +using System.Diagnostics; +using System.Runtime.CompilerServices; + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Windows.Foundation.Collections +{ + [Guid("02B51929-C1C4-4A7E-8940-0312B5C18500")] + interface IKeyValuePair + { + K Key { get; } + V Value { get; } + } +} + +namespace ABI.System.Collections.Generic +{ + using global::System; + + [Guid("02B51929-C1C4-4A7E-8940-0312B5C18500")] + public class KeyValuePair : global::Windows.Foundation.Collections.IKeyValuePair + { + public static IObjectReference CreateMarshaler(global::System.Collections.Generic.KeyValuePair obj) => + MarshalInterface>.CreateMarshaler(obj); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static object CreateRcw(IInspectable obj) + { + var pair = new KeyValuePair(obj.As()); + return (object)new global::System.Collections.Generic.KeyValuePair(pair.Key, pair.Value); + } + + public static global::System.Collections.Generic.KeyValuePair FromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return default; + } + var pair = new KeyValuePair(KeyValuePair._FromAbi(thisPtr)); + return new global::System.Collections.Generic.KeyValuePair(pair.Key, pair.Value); + } + + public static IntPtr FromManaged(global::System.Collections.Generic.KeyValuePair obj) => + CreateMarshaler(obj)?.GetRef() ?? IntPtr.Zero; + + public static (int length, IntPtr data) FromManagedArray(global::System.Collections.Generic.KeyValuePair[] array) => + MarshalInterfaceHelper>.FromManagedArray(array, (o) => FromManaged(o)); + + public static void DisposeMarshaler(IObjectReference value) => + MarshalInterfaceHelper>.DisposeMarshaler(value); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(KeyValuePair)); + + internal sealed class ToIKeyValuePair : global::Windows.Foundation.Collections.IKeyValuePair + { + private readonly global::System.Collections.Generic.KeyValuePair _pair; + + public ToIKeyValuePair([In] ref global::System.Collections.Generic.KeyValuePair pair) => _pair = pair; + + public K Key => _pair.Key; + + public V Value => _pair.Value; + } + + internal struct Enumerator : global::System.Collections.Generic.IEnumerator> + { + private readonly global::System.Collections.Generic.IEnumerator> _enum; + + internal Enumerator(global::System.Collections.Generic.IEnumerator> enumerator) => _enum = enumerator; + + public bool MoveNext() => _enum.MoveNext(); + + public global::Windows.Foundation.Collections.IKeyValuePair Current + { + get + { + var current = _enum.Current; + return new ToIKeyValuePair(ref current); + } + } + + object IEnumerator.Current => Current; + + void IEnumerator.Reset() => _enum.Reset(); + + public void Dispose() { } + } + + [Guid("02B51929-C1C4-4A7E-8940-0312B5C18500")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate get_Key_0; + public global::System.Delegate get_Value_1; + public static Guid PIID = GuidGenerator.CreateIID(typeof(KeyValuePair)); + private static readonly Type get_Key_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType.MakeByRefType(), typeof(int) }); + private static readonly Type get_Value_1_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType.MakeByRefType(), typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + get_Key_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], get_Key_0_Type); + get_Value_1 = Marshal.GetDelegateForFunctionPointer(vftbl[7], get_Value_1_Type); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + get_Key_0 = global::System.Delegate.CreateDelegate(get_Key_0_Type, typeof(Vftbl).GetMethod("Do_Abi_get_Key_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + get_Value_1 = global::System.Delegate.CreateDelegate(get_Value_1_Type, typeof(Vftbl).GetMethod("Do_Abi_get_Value_1", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)) + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 2); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Key_0); + nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Value_1); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable _adapterTable = + new ConditionalWeakTable(); + + private static ToIKeyValuePair FindAdapter(IntPtr thisPtr) + { + var __this = (global::System.Collections.Generic.KeyValuePair)global::WinRT.ComWrappersSupport.FindObject(thisPtr); + return _adapterTable.GetValue(__this, (pair) => new ToIKeyValuePair(ref __this)); + } + + private static unsafe int Do_Abi_get_Key_0(void* thisPtr, out KAbi __return_value__) + { + K ____return_value__ = default; + __return_value__ = default; + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Key; + __return_value__ = (KAbi)Marshaler.FromManaged(____return_value__); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_get_Value_1(void* thisPtr, out VAbi __return_value__) + { + V ____return_value__ = default; + __return_value__ = default; + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Value; + __return_value__ = (VAbi)Marshaler.FromManaged(____return_value__); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + public static ObjectReference _FromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + + public static Guid PIID = Vftbl.PIID; + + public static implicit operator KeyValuePair(IObjectReference obj) => (obj != null) ? new KeyValuePair(obj) : null; + public static implicit operator KeyValuePair(ObjectReference obj) => (obj != null) ? new KeyValuePair(obj) : null; + protected readonly ObjectReference _obj; + public IObjectReference ObjRef { get => _obj; } + + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public KeyValuePair(IObjectReference obj) : this(obj.As()) { } + public KeyValuePair(ObjectReference obj) + { + _obj = obj; + } + + public unsafe K Key + { + get + { + var __params = new object[] { ThisPtr, null }; + try + { + _obj.Vftbl.get_Key_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[1]); + } + finally + { + Marshaler.DisposeAbi(__params[1]); + } + } + } + + public unsafe V Value + { + get + { + var __params = new object[] { ThisPtr, null }; + try + { + _obj.Vftbl.get_Value_1.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[1]); + } + finally + { + Marshaler.DisposeAbi(__params[1]); + } + } + } + } +} \ No newline at end of file diff --git a/WinRT.Runtime/Projections/KeyValuePair.cs b/WinRT.Runtime/Projections/KeyValuePair.netstandard2.0.cs similarity index 97% rename from WinRT.Runtime/Projections/KeyValuePair.cs rename to WinRT.Runtime/Projections/KeyValuePair.netstandard2.0.cs index 79ce2a14a..b6c8a789e 100644 --- a/WinRT.Runtime/Projections/KeyValuePair.cs +++ b/WinRT.Runtime/Projections/KeyValuePair.netstandard2.0.cs @@ -1,243 +1,243 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.InteropServices; -using WinRT; -using WinRT.Interop; -using System.Diagnostics; -using System.Runtime.CompilerServices; - -#pragma warning disable 0169 // warning CS0169: The field '...' is never used -#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to - -namespace Windows.Foundation.Collections -{ - [Guid("02B51929-C1C4-4A7E-8940-0312B5C18500")] - interface IKeyValuePair - { - K Key { get; } - V Value { get; } - } -} - -namespace ABI.System.Collections.Generic -{ - using global::System; - - [Guid("02B51929-C1C4-4A7E-8940-0312B5C18500")] - public class KeyValuePair : global::Windows.Foundation.Collections.IKeyValuePair - { - public static IObjectReference CreateMarshaler(global::System.Collections.Generic.KeyValuePair obj) => - MarshalInterface>.CreateMarshaler(obj); - - public static IntPtr GetAbi(IObjectReference objRef) => - objRef?.ThisPtr ?? IntPtr.Zero; - - public static object CreateRcw(IInspectable obj) - { - var pair = new KeyValuePair(obj.As()); - return (object)new global::System.Collections.Generic.KeyValuePair(pair.Key, pair.Value); - } - - public static global::System.Collections.Generic.KeyValuePair FromAbi(IntPtr thisPtr) - { - if (thisPtr == IntPtr.Zero) - { - return default; - } - var pair = new KeyValuePair(KeyValuePair._FromAbi(thisPtr)); - return new global::System.Collections.Generic.KeyValuePair(pair.Key, pair.Value); - } - - public static IntPtr FromManaged(global::System.Collections.Generic.KeyValuePair obj) => - CreateMarshaler(obj)?.GetRef() ?? IntPtr.Zero; - - public static (int length, IntPtr data) FromManagedArray(global::System.Collections.Generic.KeyValuePair[] array) => - MarshalInterfaceHelper>.FromManagedArray(array, (o) => FromManaged(o)); - - public static void DisposeMarshaler(IObjectReference value) => - MarshalInterfaceHelper>.DisposeMarshaler(value); - - public static void DisposeAbi(IntPtr abi) => - MarshalInterfaceHelper>.DisposeAbi(abi); - - public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(KeyValuePair)); - - internal sealed class ToIKeyValuePair : global::Windows.Foundation.Collections.IKeyValuePair - { - private readonly global::System.Collections.Generic.KeyValuePair _pair; - - public ToIKeyValuePair([In] ref global::System.Collections.Generic.KeyValuePair pair) => _pair = pair; - - public K Key => _pair.Key; - - public V Value => _pair.Value; - } - - internal struct Enumerator : global::System.Collections.Generic.IEnumerator> - { - private readonly global::System.Collections.Generic.IEnumerator> _enum; - - internal Enumerator(global::System.Collections.Generic.IEnumerator> enumerator) => _enum = enumerator; - - public bool MoveNext() => _enum.MoveNext(); - - public global::Windows.Foundation.Collections.IKeyValuePair Current - { - get - { - var current = _enum.Current; - return new ToIKeyValuePair(ref current); - } - } - - object IEnumerator.Current => Current; - - void IEnumerator.Reset() => _enum.Reset(); - - public void Dispose() { } - } - - [Guid("02B51929-C1C4-4A7E-8940-0312B5C18500")] - public struct Vftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - public global::System.Delegate get_Key_0; - public global::System.Delegate get_Value_1; - public static Guid PIID = GuidGenerator.CreateIID(typeof(KeyValuePair)); - private static readonly Type get_Key_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType.MakeByRefType(), typeof(int) }); - private static readonly Type get_Value_1_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType.MakeByRefType(), typeof(int) }); - - internal unsafe Vftbl(IntPtr thisPtr) - { - var vftblPtr = Marshal.PtrToStructure(thisPtr); - var vftbl = (IntPtr*)vftblPtr.Vftbl; - IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); - get_Key_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], get_Key_0_Type); - get_Value_1 = Marshal.GetDelegateForFunctionPointer(vftbl[7], get_Value_1_Type); - } - - private static readonly Vftbl AbiToProjectionVftable; - public static readonly IntPtr AbiToProjectionVftablePtr; - static unsafe Vftbl() - { - AbiToProjectionVftable = new Vftbl - { - IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, - get_Key_0 = global::System.Delegate.CreateDelegate(get_Key_0_Type, typeof(Vftbl).GetMethod("Do_Abi_get_Key_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), - get_Value_1 = global::System.Delegate.CreateDelegate(get_Value_1_Type, typeof(Vftbl).GetMethod("Do_Abi_get_Value_1", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)) - }; - var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 2); - Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); - nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Key_0); - nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Value_1); - - AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; - } - - private static ConditionalWeakTable _adapterTable = - new ConditionalWeakTable(); - - private static ToIKeyValuePair FindAdapter(IntPtr thisPtr) - { - var __this = (global::System.Collections.Generic.KeyValuePair)global::WinRT.ComWrappersSupport.FindObject(thisPtr); - return _adapterTable.GetValue(__this, (pair) => new ToIKeyValuePair(ref __this)); - } - - private static unsafe int Do_Abi_get_Key_0(void* thisPtr, out KAbi __return_value__) - { - K ____return_value__ = default; - __return_value__ = default; - try - { - ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Key; - __return_value__ = (KAbi)Marshaler.FromManaged(____return_value__); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - private static unsafe int Do_Abi_get_Value_1(void* thisPtr, out VAbi __return_value__) - { - V ____return_value__ = default; - __return_value__ = default; - try - { - ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Value; - __return_value__ = (VAbi)Marshaler.FromManaged(____return_value__); - } - catch (Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - } - public static ObjectReference _FromAbi(IntPtr thisPtr) - { - if (thisPtr == IntPtr.Zero) - { - return null; - } - var vftblT = new Vftbl(thisPtr); - return ObjectReference.FromAbi(thisPtr, vftblT); - } - - public static Guid PIID = Vftbl.PIID; - - public static implicit operator KeyValuePair(IObjectReference obj) => (obj != null) ? new KeyValuePair(obj) : null; - public static implicit operator KeyValuePair(ObjectReference obj) => (obj != null) ? new KeyValuePair(obj) : null; - protected readonly ObjectReference _obj; - public IObjectReference ObjRef { get => _obj; } - - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - public KeyValuePair(IObjectReference obj) : this(obj.As()) { } - public KeyValuePair(ObjectReference obj) - { - _obj = obj; - } - - public unsafe K Key - { - get - { - var __params = new object[] { ThisPtr, null }; - try - { - _obj.Vftbl.get_Key_0.DynamicInvokeAbi(__params); - return Marshaler.FromAbi(__params[1]); - } - finally - { - Marshaler.DisposeAbi(__params[1]); - } - } - } - - public unsafe V Value - { - get - { - var __params = new object[] { ThisPtr, null }; - try - { - _obj.Vftbl.get_Value_1.DynamicInvokeAbi(__params); - return Marshaler.FromAbi(__params[1]); - } - finally - { - Marshaler.DisposeAbi(__params[1]); - } - } - } - } -} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; +using System.Diagnostics; +using System.Runtime.CompilerServices; + +#pragma warning disable 0169 // warning CS0169: The field '...' is never used +#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to + +namespace Windows.Foundation.Collections +{ + [Guid("02B51929-C1C4-4A7E-8940-0312B5C18500")] + interface IKeyValuePair + { + K Key { get; } + V Value { get; } + } +} + +namespace ABI.System.Collections.Generic +{ + using global::System; + + [Guid("02B51929-C1C4-4A7E-8940-0312B5C18500")] + public class KeyValuePair : global::Windows.Foundation.Collections.IKeyValuePair + { + public static IObjectReference CreateMarshaler(global::System.Collections.Generic.KeyValuePair obj) => + MarshalInterface>.CreateMarshaler(obj); + + public static IntPtr GetAbi(IObjectReference objRef) => + objRef?.ThisPtr ?? IntPtr.Zero; + + public static object CreateRcw(IInspectable obj) + { + var pair = new KeyValuePair(obj.As()); + return (object)new global::System.Collections.Generic.KeyValuePair(pair.Key, pair.Value); + } + + public static global::System.Collections.Generic.KeyValuePair FromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return default; + } + var pair = new KeyValuePair(KeyValuePair._FromAbi(thisPtr)); + return new global::System.Collections.Generic.KeyValuePair(pair.Key, pair.Value); + } + + public static IntPtr FromManaged(global::System.Collections.Generic.KeyValuePair obj) => + CreateMarshaler(obj)?.GetRef() ?? IntPtr.Zero; + + public static (int length, IntPtr data) FromManagedArray(global::System.Collections.Generic.KeyValuePair[] array) => + MarshalInterfaceHelper>.FromManagedArray(array, (o) => FromManaged(o)); + + public static void DisposeMarshaler(IObjectReference value) => + MarshalInterfaceHelper>.DisposeMarshaler(value); + + public static void DisposeAbi(IntPtr abi) => + MarshalInterfaceHelper>.DisposeAbi(abi); + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(KeyValuePair)); + + internal sealed class ToIKeyValuePair : global::Windows.Foundation.Collections.IKeyValuePair + { + private readonly global::System.Collections.Generic.KeyValuePair _pair; + + public ToIKeyValuePair([In] ref global::System.Collections.Generic.KeyValuePair pair) => _pair = pair; + + public K Key => _pair.Key; + + public V Value => _pair.Value; + } + + internal struct Enumerator : global::System.Collections.Generic.IEnumerator> + { + private readonly global::System.Collections.Generic.IEnumerator> _enum; + + internal Enumerator(global::System.Collections.Generic.IEnumerator> enumerator) => _enum = enumerator; + + public bool MoveNext() => _enum.MoveNext(); + + public global::Windows.Foundation.Collections.IKeyValuePair Current + { + get + { + var current = _enum.Current; + return new ToIKeyValuePair(ref current); + } + } + + object IEnumerator.Current => Current; + + void IEnumerator.Reset() => _enum.Reset(); + + public void Dispose() { } + } + + [Guid("02B51929-C1C4-4A7E-8940-0312B5C18500")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate get_Key_0; + public global::System.Delegate get_Value_1; + public static Guid PIID = GuidGenerator.CreateIID(typeof(KeyValuePair)); + private static readonly Type get_Key_0_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType.MakeByRefType(), typeof(int) }); + private static readonly Type get_Value_1_Type = Expression.GetDelegateType(new Type[] { typeof(void*), Marshaler.AbiType.MakeByRefType(), typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + get_Key_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], get_Key_0_Type); + get_Value_1 = Marshal.GetDelegateForFunctionPointer(vftbl[7], get_Value_1_Type); + } + + private static readonly Vftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + static unsafe Vftbl() + { + AbiToProjectionVftable = new Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + get_Key_0 = global::System.Delegate.CreateDelegate(get_Key_0_Type, typeof(Vftbl).GetMethod("Do_Abi_get_Key_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)), + get_Value_1 = global::System.Delegate.CreateDelegate(get_Value_1_Type, typeof(Vftbl).GetMethod("Do_Abi_get_Value_1", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)) + }; + var nativeVftbl = (IntPtr*)Marshal.AllocCoTaskMem(Marshal.SizeOf() + sizeof(IntPtr) * 2); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Key_0); + nativeVftbl[7] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Value_1); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static ConditionalWeakTable _adapterTable = + new ConditionalWeakTable(); + + private static ToIKeyValuePair FindAdapter(IntPtr thisPtr) + { + var __this = (global::System.Collections.Generic.KeyValuePair)global::WinRT.ComWrappersSupport.FindObject(thisPtr); + return _adapterTable.GetValue(__this, (pair) => new ToIKeyValuePair(ref __this)); + } + + private static unsafe int Do_Abi_get_Key_0(void* thisPtr, out KAbi __return_value__) + { + K ____return_value__ = default; + __return_value__ = default; + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Key; + __return_value__ = (KAbi)Marshaler.FromManaged(____return_value__); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + private static unsafe int Do_Abi_get_Value_1(void* thisPtr, out VAbi __return_value__) + { + V ____return_value__ = default; + __return_value__ = default; + try + { + ____return_value__ = FindAdapter(new IntPtr(thisPtr)).Value; + __return_value__ = (VAbi)Marshaler.FromManaged(____return_value__); + } + catch (Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } + public static ObjectReference _FromAbi(IntPtr thisPtr) + { + if (thisPtr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(thisPtr); + return ObjectReference.FromAbi(thisPtr, vftblT); + } + + public static Guid PIID = Vftbl.PIID; + + public static implicit operator KeyValuePair(IObjectReference obj) => (obj != null) ? new KeyValuePair(obj) : null; + public static implicit operator KeyValuePair(ObjectReference obj) => (obj != null) ? new KeyValuePair(obj) : null; + protected readonly ObjectReference _obj; + public IObjectReference ObjRef { get => _obj; } + + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public KeyValuePair(IObjectReference obj) : this(obj.As()) { } + public KeyValuePair(ObjectReference obj) + { + _obj = obj; + } + + public unsafe K Key + { + get + { + var __params = new object[] { ThisPtr, null }; + try + { + _obj.Vftbl.get_Key_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[1]); + } + finally + { + Marshaler.DisposeAbi(__params[1]); + } + } + } + + public unsafe V Value + { + get + { + var __params = new object[] { ThisPtr, null }; + try + { + _obj.Vftbl.get_Value_1.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[1]); + } + finally + { + Marshaler.DisposeAbi(__params[1]); + } + } + } + } +} diff --git a/WinRT.Runtime/Projections/NotifyCollectionChangedAction.cs b/WinRT.Runtime/Projections/NotifyCollectionChangedAction.net5.cs similarity index 94% rename from WinRT.Runtime/Projections/NotifyCollectionChangedAction.cs rename to WinRT.Runtime/Projections/NotifyCollectionChangedAction.net5.cs index f9ba0a59a..968335ce0 100644 --- a/WinRT.Runtime/Projections/NotifyCollectionChangedAction.cs +++ b/WinRT.Runtime/Projections/NotifyCollectionChangedAction.net5.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; diff --git a/WinRT.Runtime/Projections/NotifyCollectionChangedAction.netstandard2.0.cs b/WinRT.Runtime/Projections/NotifyCollectionChangedAction.netstandard2.0.cs new file mode 100644 index 000000000..968335ce0 --- /dev/null +++ b/WinRT.Runtime/Projections/NotifyCollectionChangedAction.netstandard2.0.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace ABI.System.Collections.Specialized +{ + static class NotifyCollectionChangedAction + { + public static string GetGuidSignature() => "enum(Microsoft.UI.Xaml.Interop.NotifyCollectionChangedAction;i4)"; + } +} diff --git a/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs b/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.net5.cs similarity index 99% rename from WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs rename to WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.net5.cs index dd40c971a..868a1aa98 100644 --- a/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs +++ b/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.net5.cs @@ -1,4 +1,4 @@ -using ABI.Microsoft.UI.Xaml.Interop; +using ABI.Microsoft.UI.Xaml.Interop; using System; using System.Collections.Generic; using System.ComponentModel; @@ -8,7 +8,7 @@ using WinRT.Interop; namespace ABI.Microsoft.UI.Xaml.Interop -{ +{ [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] [Guid("DA049FF2-D2E0-5FE8-8C7B-F87F26060B6F")] internal unsafe class INotifyCollectionChangedEventArgs @@ -107,7 +107,7 @@ public unsafe int OldStartingIndex } } } - + [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] [Guid("5108EBA4-4892-5A20-8374-A96815E0FD27")] internal unsafe class WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory diff --git a/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.netstandard2.0.cs b/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.netstandard2.0.cs new file mode 100644 index 000000000..868a1aa98 --- /dev/null +++ b/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.netstandard2.0.cs @@ -0,0 +1,242 @@ +using ABI.Microsoft.UI.Xaml.Interop; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; +using WinRT; +using WinRT.Interop; + +namespace ABI.Microsoft.UI.Xaml.Interop +{ + [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] + [Guid("DA049FF2-D2E0-5FE8-8C7B-F87F26060B6F")] + internal unsafe class INotifyCollectionChangedEventArgs + { + [Guid("DA049FF2-D2E0-5FE8-8C7B-F87F26060B6F")] + [StructLayout(LayoutKind.Sequential)] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + private void* _get_Action_0; + public delegate* stdcall get_Action_0 => (delegate* stdcall)_get_Action_0; + private void* _get_NewItems_1; + public delegate* stdcall get_NewItems_1 => (delegate* stdcall)_get_NewItems_1; + private void* _get_OldItems_2; + public delegate* stdcall get_OldItems_2 => (delegate* stdcall)_get_OldItems_2; + private void* _get_NewStartingIndex_3; + public delegate* stdcall get_NewStartingIndex_3 => (delegate* stdcall)_get_NewStartingIndex_3; + private void* _get_OldStartingIndex_4; + public delegate* stdcall get_OldStartingIndex_4 => (delegate* stdcall)_get_OldStartingIndex_4; + } + internal static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + public static implicit operator INotifyCollectionChangedEventArgs(IObjectReference obj) => (obj != null) ? new INotifyCollectionChangedEventArgs(obj) : null; + protected readonly ObjectReference _obj; + public IObjectReference ObjRef { get => _obj; } + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public INotifyCollectionChangedEventArgs(IObjectReference obj) : this(obj.As()) { } + internal INotifyCollectionChangedEventArgs(ObjectReference obj) + { + _obj = obj; + } + + public unsafe global::System.Collections.Specialized.NotifyCollectionChangedAction Action + { + get + { + global::System.Collections.Specialized.NotifyCollectionChangedAction __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Action_0(ThisPtr, &__retval)); + return __retval; + } + } + + public unsafe global::System.Collections.IList NewItems + { + get + { + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_NewItems_1(ThisPtr, &__retval)); + return MarshalInterface.FromAbi(__retval); + } + finally + { + MarshalInterface.DisposeAbi(__retval); + } + } + } + + public unsafe int NewStartingIndex + { + get + { + int __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_NewStartingIndex_3(ThisPtr, &__retval)); + return __retval; + } + } + + public unsafe global::System.Collections.IList OldItems + { + get + { + IntPtr __retval = default; + try + { + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_OldItems_2(ThisPtr, &__retval)); + return MarshalInterface.FromAbi(__retval); + } + finally + { + MarshalInterface.DisposeAbi(__retval); + } + } + } + + public unsafe int OldStartingIndex + { + get + { + int __retval = default; + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_OldStartingIndex_4(ThisPtr, &__retval)); + return __retval; + } + } + } + + [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] + [Guid("5108EBA4-4892-5A20-8374-A96815E0FD27")] + internal unsafe class WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory + { + [Guid("5108EBA4-4892-5A20-8374-A96815E0FD27")] + [StructLayout(LayoutKind.Sequential)] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + private void* _CreateInstanceWithAllParameters_0; + public delegate* stdcall CreateInstanceWithAllParameters_0 => (delegate* stdcall)_CreateInstanceWithAllParameters_0; + } + public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + public static implicit operator WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory(IObjectReference obj) => (obj != null) ? new WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory(obj) : null; + public static implicit operator WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory(ObjectReference obj) => (obj != null) ? new WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory(obj) : null; + protected readonly ObjectReference _obj; + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory(IObjectReference obj) : this(obj.As()) { } + public WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory(ObjectReference obj) + { + _obj = obj; + } + public unsafe IObjectReference CreateInstanceWithAllParameters(global::System.Collections.Specialized.NotifyCollectionChangedAction action, global::System.Collections.IList newItems, global::System.Collections.IList oldItems, int newIndex, int oldIndex, object baseInterface, out IObjectReference innerInterface) + { + IObjectReference __newItems = default; + IObjectReference __oldItems = default; + IObjectReference __baseInterface = default; + IntPtr __innerInterface = default; + IntPtr __retval = default; + try + { + __newItems = MarshalInterface.CreateMarshaler(newItems); + __oldItems = MarshalInterface.CreateMarshaler(oldItems); + __baseInterface = MarshalInspectable.CreateMarshaler(baseInterface); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.CreateInstanceWithAllParameters_0(ThisPtr, action, MarshalInterface.GetAbi(__newItems), MarshalInterface.GetAbi(__oldItems), newIndex, oldIndex, MarshalInspectable.GetAbi(__baseInterface), out __innerInterface, out __retval)); + innerInterface = ObjectReference.FromAbi(__innerInterface); + return ObjectReference.FromAbi(__retval); + } + finally + { + MarshalInterface.DisposeMarshaler(__newItems); + MarshalInterface.DisposeMarshaler(__oldItems); + MarshalInspectable.DisposeMarshaler(__baseInterface); + MarshalInspectable.DisposeAbi(__innerInterface); + MarshalInspectable.DisposeAbi(__retval); + } + } + } +} + +namespace ABI.System.Collections.Specialized +{ + [EditorBrowsable(EditorBrowsableState.Never)] + [StructLayout(LayoutKind.Sequential)] + public struct NotifyCollectionChangedEventArgs + { + private static WeakLazy _propertyChangedArgsFactory = new WeakLazy(); + + private class ActivationFactory : BaseActivationFactory + { + public ActivationFactory() : base("Microsoft.UI.Xaml.Interop", "Microsoft.UI.Xaml.Interop.NotifyCollectionChangedEventArgs") + { + } + } + + public static IObjectReference CreateMarshaler(global::System.Collections.Specialized.NotifyCollectionChangedEventArgs value) + { + if (value is null) + { + return null; + } + + WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory factory = _propertyChangedArgsFactory.Value._As(); + return factory.CreateInstanceWithAllParameters(value.Action, value.NewItems, value.OldItems, value.NewStartingIndex, value.OldStartingIndex, null, out _); + } + + public static IntPtr GetAbi(IObjectReference m) => m?.ThisPtr ?? IntPtr.Zero; + + public static global::System.Collections.Specialized.NotifyCollectionChangedEventArgs FromAbi(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + { + return null; + } + + INotifyCollectionChangedEventArgs args = INotifyCollectionChangedEventArgs.FromAbi(ptr); + return CreateNotifyCollectionChangedEventArgs(args.Action, args.NewItems, args.OldItems, args.NewStartingIndex, args.OldStartingIndex); + } + + private static global::System.Collections.Specialized.NotifyCollectionChangedEventArgs CreateNotifyCollectionChangedEventArgs( + global::System.Collections.Specialized.NotifyCollectionChangedAction action, + global::System.Collections.IList newItems, + global::System.Collections.IList oldItems, + int newStartingIndex, + int oldStartingIndex) => + action switch + { + global::System.Collections.Specialized.NotifyCollectionChangedAction.Add => new global::System.Collections.Specialized.NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex), + global::System.Collections.Specialized.NotifyCollectionChangedAction.Remove => new global::System.Collections.Specialized.NotifyCollectionChangedEventArgs(action, oldItems, oldStartingIndex), + global::System.Collections.Specialized.NotifyCollectionChangedAction.Replace => new global::System.Collections.Specialized.NotifyCollectionChangedEventArgs(action, newItems, oldItems, newStartingIndex), + global::System.Collections.Specialized.NotifyCollectionChangedAction.Move => new global::System.Collections.Specialized.NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex, oldStartingIndex), + global::System.Collections.Specialized.NotifyCollectionChangedAction.Reset => new global::System.Collections.Specialized.NotifyCollectionChangedEventArgs(global::System.Collections.Specialized.NotifyCollectionChangedAction.Reset), + _ => throw new ArgumentException(), + }; + + public static unsafe void CopyManaged(global::System.Collections.Specialized.NotifyCollectionChangedEventArgs o, IntPtr dest) + { + using var objRef = CreateMarshaler(o); + *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero; + } + + public static IntPtr FromManaged(global::System.Collections.Specialized.NotifyCollectionChangedEventArgs value) + { + if (value is null) + { + return IntPtr.Zero; + } + return CreateMarshaler(value).GetRef(); + } + + public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } + public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } + + public static string GetGuidSignature() + { + return "rc(Microsoft.UI.Xaml.Interop.NotifyCollectionChangedEventArgs;{4cf68d33-e3f2-4964-b85e-945b4f7e2f21})"; + } + } +} diff --git a/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs b/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.net5.cs similarity index 99% rename from WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs rename to WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.net5.cs index d539114b1..4448430f7 100644 --- a/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs +++ b/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.net5.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; @@ -7,7 +7,7 @@ namespace ABI.System.Collections.Specialized { - + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] [Guid("8B0909DC-2005-5D93-BF8A-725F017BAA8D")] public static class NotifyCollectionChangedEventHandler @@ -32,7 +32,7 @@ static NotifyCollectionChangedEventHandler() public static global::System.Delegate AbiInvokeDelegate { get; } - public static unsafe IObjectReference CreateMarshaler(global::System.Collections.Specialized.NotifyCollectionChangedEventHandler managedDelegate) => + public static unsafe IObjectReference CreateMarshaler(global::System.Collections.Specialized.NotifyCollectionChangedEventHandler managedDelegate) => managedDelegate is null ? null : ComWrappersSupport.CreateCCWForObject(managedDelegate).As(GuidGenerator.GetIID(typeof(NotifyCollectionChangedEventHandler))); public static IntPtr GetAbi(IObjectReference value) => MarshalInterfaceHelper.GetAbi(value); @@ -46,25 +46,25 @@ public static unsafe IObjectReference CreateMarshaler(global::System.Collections [global::WinRT.ObjectReferenceWrapper(nameof(_nativeDelegate))] private class NativeDelegateWrapper { - private readonly ObjectReference _nativeDelegate; + private readonly ObjectReference _nativeDelegate; private readonly AgileReference _agileReference = default; public NativeDelegateWrapper(ObjectReference nativeDelegate) { - _nativeDelegate = nativeDelegate; - if (_nativeDelegate.TryAs(out var objRef) < 0) - { - _agileReference = new AgileReference(_nativeDelegate); - } - else - { - objRef.Dispose(); - } + _nativeDelegate = nativeDelegate; + if (_nativeDelegate.TryAs(out var objRef) < 0) + { + _agileReference = new AgileReference(_nativeDelegate); + } + else + { + objRef.Dispose(); + } } public void Invoke(object sender, global::System.Collections.Specialized.NotifyCollectionChangedEventArgs e) - { - using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(NotifyCollectionChangedEventHandler))); + { + using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(NotifyCollectionChangedEventHandler))); var delegateToInvoke = agileDelegate ?? _nativeDelegate; IntPtr ThisPtr = delegateToInvoke.ThisPtr; var abiInvoke = Marshal.GetDelegateForFunctionPointer(delegateToInvoke.Vftbl.Invoke); @@ -85,7 +85,7 @@ public void Invoke(object sender, global::System.Collections.Specialized.NotifyC } } - public static IntPtr FromManaged(global::System.Collections.Specialized.NotifyCollectionChangedEventHandler managedDelegate) => + public static IntPtr FromManaged(global::System.Collections.Specialized.NotifyCollectionChangedEventHandler managedDelegate) => managedDelegate is null ? IntPtr.Zero : CreateMarshaler(managedDelegate).GetRef(); public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper.DisposeMarshaler(value); diff --git a/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.netstandard2.0.cs b/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.netstandard2.0.cs new file mode 100644 index 000000000..4448430f7 --- /dev/null +++ b/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.netstandard2.0.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using WinRT; +using WinRT.Interop; + +namespace ABI.System.Collections.Specialized +{ + + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + [Guid("8B0909DC-2005-5D93-BF8A-725F017BAA8D")] + public static class NotifyCollectionChangedEventHandler + { + private unsafe delegate int Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e); + + private static readonly global::WinRT.Interop.IDelegateVftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static NotifyCollectionChangedEventHandler() + { + AbiInvokeDelegate = new Abi_Invoke(Do_Abi_Invoke); + AbiToProjectionVftable = new global::WinRT.Interop.IDelegateVftbl + { + IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, + Invoke = Marshal.GetFunctionPointerForDelegate(AbiInvokeDelegate) + }; + var nativeVftbl = ComWrappersSupport.AllocateVtableMemory(typeof(NotifyCollectionChangedEventHandler), Marshal.SizeOf()); + Marshal.StructureToPtr(AbiToProjectionVftable, nativeVftbl, false); + AbiToProjectionVftablePtr = nativeVftbl; + } + + public static global::System.Delegate AbiInvokeDelegate { get; } + + public static unsafe IObjectReference CreateMarshaler(global::System.Collections.Specialized.NotifyCollectionChangedEventHandler managedDelegate) => + managedDelegate is null ? null : ComWrappersSupport.CreateCCWForObject(managedDelegate).As(GuidGenerator.GetIID(typeof(NotifyCollectionChangedEventHandler))); + + public static IntPtr GetAbi(IObjectReference value) => MarshalInterfaceHelper.GetAbi(value); + + public static unsafe global::System.Collections.Specialized.NotifyCollectionChangedEventHandler FromAbi(IntPtr nativeDelegate) + { + var abiDelegate = ObjectReference.FromAbi(nativeDelegate); + 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))] + private class NativeDelegateWrapper + { + private readonly ObjectReference _nativeDelegate; + private readonly AgileReference _agileReference = default; + + public NativeDelegateWrapper(ObjectReference nativeDelegate) + { + _nativeDelegate = nativeDelegate; + if (_nativeDelegate.TryAs(out var objRef) < 0) + { + _agileReference = new AgileReference(_nativeDelegate); + } + else + { + objRef.Dispose(); + } + } + + public void Invoke(object sender, global::System.Collections.Specialized.NotifyCollectionChangedEventArgs e) + { + using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(NotifyCollectionChangedEventHandler))); + var delegateToInvoke = agileDelegate ?? _nativeDelegate; + IntPtr ThisPtr = delegateToInvoke.ThisPtr; + var abiInvoke = Marshal.GetDelegateForFunctionPointer(delegateToInvoke.Vftbl.Invoke); + IObjectReference __sender = default; + IObjectReference __e = default; + try + { + __sender = MarshalInspectable.CreateMarshaler(sender); + __e = global::ABI.System.Collections.Specialized.NotifyCollectionChangedEventArgs.CreateMarshaler(e); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(abiInvoke(ThisPtr, MarshalInspectable.GetAbi(__sender), global::ABI.System.Collections.Specialized.NotifyCollectionChangedEventArgs.GetAbi(__e))); + } + finally + { + MarshalInspectable.DisposeMarshaler(__sender); + global::ABI.System.Collections.Specialized.NotifyCollectionChangedEventArgs.DisposeMarshaler(__e); + } + + } + } + + public static IntPtr FromManaged(global::System.Collections.Specialized.NotifyCollectionChangedEventHandler managedDelegate) => + managedDelegate is null ? IntPtr.Zero : CreateMarshaler(managedDelegate).GetRef(); + + public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper.DisposeMarshaler(value); + + public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper.DisposeAbi(abi); + + private static unsafe int Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e) + { + try + { + global::WinRT.ComWrappersSupport.MarshalDelegateInvoke(thisPtr, (global::System.Collections.Specialized.NotifyCollectionChangedEventHandler invoke) => + { + invoke(MarshalInspectable.FromAbi(sender), global::ABI.System.Collections.Specialized.NotifyCollectionChangedEventArgs.FromAbi(e)); + }); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } +} diff --git a/WinRT.Runtime/Projections/Nullable.cs b/WinRT.Runtime/Projections/Nullable.net5.cs similarity index 99% rename from WinRT.Runtime/Projections/Nullable.cs rename to WinRT.Runtime/Projections/Nullable.net5.cs index 1844e5da7..517a21886 100644 --- a/WinRT.Runtime/Projections/Nullable.cs +++ b/WinRT.Runtime/Projections/Nullable.net5.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; diff --git a/WinRT.Runtime/Projections/Nullable.netstandard2.0.cs b/WinRT.Runtime/Projections/Nullable.netstandard2.0.cs new file mode 100644 index 000000000..517a21886 --- /dev/null +++ b/WinRT.Runtime/Projections/Nullable.netstandard2.0.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using WinRT; +using WinRT.Interop; + +namespace ABI.Windows.Foundation +{ + using System; + + internal static class BoxedValueIReferenceImpl + { + private static Nullable.Vftbl AbiToProjectionVftable; + public static IntPtr AbiToProjectionVftablePtr; + + static unsafe BoxedValueIReferenceImpl() + { + AbiToProjectionVftable = new Nullable.Vftbl + { + IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, + get_Value_0 = global::System.Delegate.CreateDelegate(Nullable.Vftbl.get_Value_0_Type, typeof(BoxedValueIReferenceImpl).GetMethod("Do_Abi_get_Value_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)) + }; + var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(BoxedValueIReferenceImpl), Marshal.SizeOf() + sizeof(IntPtr) * 1); + Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); + nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Value_0); + + AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; + } + + private static unsafe int Do_Abi_get_Value_0(void* thisPtr, out TAbi __return_value__) + { + T ____return_value__ = default; + + __return_value__ = default; + + try + { + ____return_value__ = (T)global::WinRT.ComWrappersSupport.FindObject(new IntPtr(thisPtr)); + __return_value__ = (TAbi)Marshaler.FromManaged(____return_value__); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } +} + +namespace ABI.System +{ + [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] + [Guid("61C17706-2D65-11E0-9AE8-D48564015472")] + public class Nullable + { + public static IObjectReference CreateMarshaler(object value) + { + if (value is null) + { + return null; + } + return ComWrappersSupport.CreateCCWForObject(value).As(PIID); + } + + public static IntPtr GetAbi(IObjectReference m) => m?.ThisPtr ?? IntPtr.Zero; + + public static object FromAbi(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + { + return null; + } + var vftblT = new Vftbl(ptr); + var wrapper = new Nullable(ObjectReference.FromAbi(ptr, vftblT)); + return wrapper.Value; + } + + public static unsafe void CopyManaged(object o, IntPtr dest) + { + using var objRef = CreateMarshaler(o); + *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero; + } + + public static IntPtr FromManaged(object value) + { + if (value is null) + { + return IntPtr.Zero; + } + return CreateMarshaler(value).GetRef(); + } + + public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } + public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } + + public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(Nullable)); + + [Guid("61C17706-2D65-11E0-9AE8-D48564015472")] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public global::System.Delegate get_Value_0; + public static Guid PIID = GuidGenerator.CreateIID(typeof(Nullable)); + public static readonly global::System.Type get_Value_0_Type = Expression.GetDelegateType(new global::System.Type[] { typeof(void*), Marshaler.AbiType.MakeByRefType(), typeof(int) }); + + internal unsafe Vftbl(IntPtr thisPtr) + { + var vftblPtr = Marshal.PtrToStructure(thisPtr); + var vftbl = (IntPtr*)vftblPtr.Vftbl; + IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); + get_Value_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], get_Value_0_Type); + } + } + + public static Guid PIID = Vftbl.PIID; + + public static implicit operator Nullable(IObjectReference obj) => (obj != null) ? new Nullable(obj) : null; + public static implicit operator Nullable(ObjectReference obj) => (obj != null) ? new Nullable(obj) : null; + protected readonly ObjectReference _obj; + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public Nullable(IObjectReference obj) : this(obj.As()) { } + public Nullable(ObjectReference obj) + { + _obj = obj; + } + + public unsafe T Value + { + get + { + var __params = new object[] { ThisPtr, null }; + try + { + _obj.Vftbl.get_Value_0.DynamicInvokeAbi(__params); + return Marshaler.FromAbi(__params[1]); + } + finally + { + Marshaler.DisposeAbi(__params[1]); + } + } + } + } +} diff --git a/WinRT.Runtime/Projections/Numerics.cs b/WinRT.Runtime/Projections/Numerics.net5.cs similarity index 98% rename from WinRT.Runtime/Projections/Numerics.cs rename to WinRT.Runtime/Projections/Numerics.net5.cs index c8e2d96c5..3b6ac2671 100644 --- a/WinRT.Runtime/Projections/Numerics.cs +++ b/WinRT.Runtime/Projections/Numerics.net5.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; @@ -6,50 +6,50 @@ namespace ABI.System.Numerics { [StructLayout(LayoutKind.Sequential)] - public struct Matrix3x2 - { + public struct Matrix3x2 + { public static string GetGuidSignature() => "struct(Windows.Foundation.Numerics.Matrix3x2;f4;f4;f4;f4;f4;f4)"; } [StructLayout(LayoutKind.Sequential)] - public struct Matrix4x4 - { + public 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 - { + public 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 - { + public struct Quaternion + { public static string GetGuidSignature() => "struct(Windows.Foundation.Numerics.Quaternion;f4;f4;f4;f4)"; } [StructLayout(LayoutKind.Sequential)] - public struct Vector2 - { + public struct Vector2 + { public static string GetGuidSignature() => "struct(Windows.Foundation.Numerics.Vector2;f4;f4)"; } [StructLayout(LayoutKind.Sequential)] - public struct Vector3 - { + public struct Vector3 + { public static string GetGuidSignature() => "struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4)"; } [StructLayout(LayoutKind.Sequential)] - public struct Vector4 - { + public struct Vector4 + { public static string GetGuidSignature() => "struct(Windows.Foundation.Numerics.Vector4;f4;f4;f4;f4)"; } diff --git a/WinRT.Runtime/Projections/Numerics.netstandard2.0.cs b/WinRT.Runtime/Projections/Numerics.netstandard2.0.cs new file mode 100644 index 000000000..3b6ac2671 --- /dev/null +++ b/WinRT.Runtime/Projections/Numerics.netstandard2.0.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +namespace ABI.System.Numerics +{ + [StructLayout(LayoutKind.Sequential)] + public struct Matrix3x2 + { + public static string GetGuidSignature() => + "struct(Windows.Foundation.Numerics.Matrix3x2;f4;f4;f4;f4;f4;f4)"; + } + + [StructLayout(LayoutKind.Sequential)] + public 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 + { + public static string GetGuidSignature() => + "struct(Windows.Foundation.Numerics.Plane;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);f4)"; + } + + [StructLayout(LayoutKind.Sequential)] + public struct Quaternion + { + public static string GetGuidSignature() => + "struct(Windows.Foundation.Numerics.Quaternion;f4;f4;f4;f4)"; + } + + [StructLayout(LayoutKind.Sequential)] + public struct Vector2 + { + public static string GetGuidSignature() => + "struct(Windows.Foundation.Numerics.Vector2;f4;f4)"; + } + + [StructLayout(LayoutKind.Sequential)] + public struct Vector3 + { + public static string GetGuidSignature() => + "struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4)"; + } + + [StructLayout(LayoutKind.Sequential)] + public struct Vector4 + { + public static string GetGuidSignature() => + "struct(Windows.Foundation.Numerics.Vector4;f4;f4;f4;f4)"; + } +} diff --git a/WinRT.Runtime/Projections/PropertyChangedEventArgs.cs b/WinRT.Runtime/Projections/PropertyChangedEventArgs.net5.cs similarity index 99% rename from WinRT.Runtime/Projections/PropertyChangedEventArgs.cs rename to WinRT.Runtime/Projections/PropertyChangedEventArgs.net5.cs index 4d0665fdf..9809aefe2 100644 --- a/WinRT.Runtime/Projections/PropertyChangedEventArgs.cs +++ b/WinRT.Runtime/Projections/PropertyChangedEventArgs.net5.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; @@ -15,9 +15,9 @@ internal unsafe struct IPropertyChangedEventArgsVftbl internal IInspectable.Vftbl IInspectableVftbl; private void* _get_PropertyName_0; public delegate* stdcall get_PropertyName_0 => (delegate* stdcall)_get_PropertyName_0; - } + } + - [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] [Guid("7C0C27A8-0B41-5070-B160-FC9AE960A36C")] internal unsafe class WinRTPropertyChangedEventArgsRuntimeClassFactory diff --git a/WinRT.Runtime/Projections/PropertyChangedEventArgs.netstandard2.0.cs b/WinRT.Runtime/Projections/PropertyChangedEventArgs.netstandard2.0.cs new file mode 100644 index 000000000..9809aefe2 --- /dev/null +++ b/WinRT.Runtime/Projections/PropertyChangedEventArgs.netstandard2.0.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; +using WinRT; +using WinRT.Interop; + +namespace ABI.Microsoft.UI.Xaml.Data +{ + [Guid("63D0C952-396B-54F4-AF8C-BA8724A427BF")] + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct IPropertyChangedEventArgsVftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + private void* _get_PropertyName_0; + public delegate* stdcall get_PropertyName_0 => (delegate* stdcall)_get_PropertyName_0; + } + + + [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] + [Guid("7C0C27A8-0B41-5070-B160-FC9AE960A36C")] + internal unsafe class WinRTPropertyChangedEventArgsRuntimeClassFactory + { + [Guid("7C0C27A8-0B41-5070-B160-FC9AE960A36C")] + [StructLayout(LayoutKind.Sequential)] + public struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + private void* _CreateInstance_0; + public delegate* stdcall CreateInstance_0 => (delegate* stdcall)_CreateInstance_0; + } + public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + public static implicit operator WinRTPropertyChangedEventArgsRuntimeClassFactory(IObjectReference obj) => (obj != null) ? new WinRTPropertyChangedEventArgsRuntimeClassFactory(obj) : null; + public static implicit operator WinRTPropertyChangedEventArgsRuntimeClassFactory(ObjectReference obj) => (obj != null) ? new WinRTPropertyChangedEventArgsRuntimeClassFactory(obj) : null; + protected readonly ObjectReference _obj; + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public WinRTPropertyChangedEventArgsRuntimeClassFactory(IObjectReference obj) : this(obj.As()) { } + public WinRTPropertyChangedEventArgsRuntimeClassFactory(ObjectReference obj) + { + _obj = obj; + } + + public unsafe IObjectReference CreateInstance(string name, object baseInterface, out IObjectReference innerInterface) + { + MarshalString __name = default; + IObjectReference __baseInterface = default; + IntPtr __innerInterface = default; + IntPtr __retval = default; + try + { + __name = MarshalString.CreateMarshaler(name); + __baseInterface = MarshalInspectable.CreateMarshaler(baseInterface); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.CreateInstance_0(ThisPtr, MarshalString.GetAbi(__name), MarshalInspectable.GetAbi(__baseInterface), &__innerInterface, &__retval)); + innerInterface = ObjectReference.FromAbi(__innerInterface); + return ObjectReference.Attach(ref __retval); + } + finally + { + MarshalString.DisposeMarshaler(__name); + MarshalInspectable.DisposeMarshaler(__baseInterface); + MarshalInspectable.DisposeAbi(__innerInterface); + MarshalInspectable.DisposeAbi(__retval); + } + } + } +} + +namespace ABI.System.ComponentModel +{ + [EditorBrowsable(EditorBrowsableState.Never)] + [StructLayout(LayoutKind.Sequential)] + public unsafe struct PropertyChangedEventArgs + { + private static WeakLazy _propertyChangedArgsFactory = new WeakLazy(); + + private class ActivationFactory : BaseActivationFactory + { + public ActivationFactory() : base("Microsoft.UI.Xaml.Data", "Microsoft.UI.Xaml.Data.PropertyChangedEventArgs") + { + } + } + + public static IObjectReference CreateMarshaler(global::System.ComponentModel.PropertyChangedEventArgs value) + { + if (value is null) + { + return null; + } + + ABI.Microsoft.UI.Xaml.Data.WinRTPropertyChangedEventArgsRuntimeClassFactory factory = _propertyChangedArgsFactory.Value._As(); + return factory.CreateInstance(value.PropertyName, null, out _); + } + + public static IntPtr GetAbi(IObjectReference m) => m?.ThisPtr ?? IntPtr.Zero; + + public static global::System.ComponentModel.PropertyChangedEventArgs FromAbi(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + { + return null; + } + + using var args = ObjectReference.FromAbi(ptr); + IntPtr propertyName = IntPtr.Zero; + try + { + ExceptionHelpers.ThrowExceptionForHR(args.Vftbl.get_PropertyName_0(args.ThisPtr, &propertyName)); + return new global::System.ComponentModel.PropertyChangedEventArgs(MarshalString.FromAbi(propertyName)); + } + finally + { + MarshalString.DisposeAbi(propertyName); + } + } + + public static unsafe void CopyManaged(global::System.ComponentModel.PropertyChangedEventArgs o, IntPtr dest) + { + using var objRef = CreateMarshaler(o); + *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero; + } + + public static IntPtr FromManaged(global::System.ComponentModel.PropertyChangedEventArgs value) + { + if (value is null) + { + return IntPtr.Zero; + } + return CreateMarshaler(value).GetRef(); + } + + public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } + public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } + + public static string GetGuidSignature() + { + return "rc(Microsoft.UI.Xaml.Data.NotifyPropertyChangedEventArgs;{4f33a9a0-5cf4-47a4-b16f-d7faaf17457e})"; + } + } +} diff --git a/WinRT.Runtime/Projections/PropertyChangedEventHandler.cs b/WinRT.Runtime/Projections/PropertyChangedEventHandler.net5.cs similarity index 99% rename from WinRT.Runtime/Projections/PropertyChangedEventHandler.cs rename to WinRT.Runtime/Projections/PropertyChangedEventHandler.net5.cs index 8a69f01c2..faf539856 100644 --- a/WinRT.Runtime/Projections/PropertyChangedEventHandler.cs +++ b/WinRT.Runtime/Projections/PropertyChangedEventHandler.net5.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; @@ -31,7 +31,7 @@ static PropertyChangedEventHandler() public static global::System.Delegate AbiInvokeDelegate { get; } - public static unsafe IObjectReference CreateMarshaler(global::System.ComponentModel.PropertyChangedEventHandler managedDelegate) => + public static unsafe IObjectReference CreateMarshaler(global::System.ComponentModel.PropertyChangedEventHandler managedDelegate) => managedDelegate is null ? null : ComWrappersSupport.CreateCCWForObject(managedDelegate).As(GuidGenerator.GetIID(typeof(PropertyChangedEventHandler))); public static IntPtr GetAbi(IObjectReference value) => MarshalInterfaceHelper.GetAbi(value); @@ -45,25 +45,25 @@ public static unsafe IObjectReference CreateMarshaler(global::System.ComponentMo [global::WinRT.ObjectReferenceWrapper(nameof(_nativeDelegate))] private class NativeDelegateWrapper { - private readonly ObjectReference _nativeDelegate; + private readonly ObjectReference _nativeDelegate; private readonly AgileReference _agileReference = default; public NativeDelegateWrapper(ObjectReference nativeDelegate) { - _nativeDelegate = nativeDelegate; - if (_nativeDelegate.TryAs(out var objRef) < 0) - { - _agileReference = new AgileReference(_nativeDelegate); - } - else - { - objRef.Dispose(); - } + _nativeDelegate = nativeDelegate; + if (_nativeDelegate.TryAs(out var objRef) < 0) + { + _agileReference = new AgileReference(_nativeDelegate); + } + else + { + objRef.Dispose(); + } } public void Invoke(object sender, global::System.ComponentModel.PropertyChangedEventArgs e) - { - using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(PropertyChangedEventHandler))); + { + using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(PropertyChangedEventHandler))); var delegateToInvoke = agileDelegate ?? _nativeDelegate; IntPtr ThisPtr = delegateToInvoke.ThisPtr; var abiInvoke = Marshal.GetDelegateForFunctionPointer(delegateToInvoke.Vftbl.Invoke); @@ -84,7 +84,7 @@ public void Invoke(object sender, global::System.ComponentModel.PropertyChangedE } } - public static IntPtr FromManaged(global::System.ComponentModel.PropertyChangedEventHandler managedDelegate) => + public static IntPtr FromManaged(global::System.ComponentModel.PropertyChangedEventHandler managedDelegate) => managedDelegate is null ? IntPtr.Zero : CreateMarshaler(managedDelegate).GetRef(); public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper.DisposeMarshaler(value); diff --git a/WinRT.Runtime/Projections/PropertyChangedEventHandler.netstandard2.0.cs b/WinRT.Runtime/Projections/PropertyChangedEventHandler.netstandard2.0.cs new file mode 100644 index 000000000..faf539856 --- /dev/null +++ b/WinRT.Runtime/Projections/PropertyChangedEventHandler.netstandard2.0.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using WinRT; +using WinRT.Interop; + +namespace ABI.System.ComponentModel +{ + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + [Guid("E3DE52F6-1E32-5DA6-BB2D-B5B6096C962D")] + public static class PropertyChangedEventHandler + { + private unsafe delegate int Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e); + + private static readonly global::WinRT.Interop.IDelegateVftbl AbiToProjectionVftable; + public static readonly IntPtr AbiToProjectionVftablePtr; + + static PropertyChangedEventHandler() + { + AbiInvokeDelegate = new Abi_Invoke(Do_Abi_Invoke); + AbiToProjectionVftable = new global::WinRT.Interop.IDelegateVftbl + { + IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, + Invoke = Marshal.GetFunctionPointerForDelegate(AbiInvokeDelegate) + }; + var nativeVftbl = ComWrappersSupport.AllocateVtableMemory(typeof(PropertyChangedEventHandler), Marshal.SizeOf()); + Marshal.StructureToPtr(AbiToProjectionVftable, nativeVftbl, false); + AbiToProjectionVftablePtr = nativeVftbl; + } + + public static global::System.Delegate AbiInvokeDelegate { get; } + + public static unsafe IObjectReference CreateMarshaler(global::System.ComponentModel.PropertyChangedEventHandler managedDelegate) => + managedDelegate is null ? null : ComWrappersSupport.CreateCCWForObject(managedDelegate).As(GuidGenerator.GetIID(typeof(PropertyChangedEventHandler))); + + public static IntPtr GetAbi(IObjectReference value) => MarshalInterfaceHelper.GetAbi(value); + + public static unsafe global::System.ComponentModel.PropertyChangedEventHandler FromAbi(IntPtr nativeDelegate) + { + var abiDelegate = ObjectReference.FromAbi(nativeDelegate); + 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))] + private class NativeDelegateWrapper + { + private readonly ObjectReference _nativeDelegate; + private readonly AgileReference _agileReference = default; + + public NativeDelegateWrapper(ObjectReference nativeDelegate) + { + _nativeDelegate = nativeDelegate; + if (_nativeDelegate.TryAs(out var objRef) < 0) + { + _agileReference = new AgileReference(_nativeDelegate); + } + else + { + objRef.Dispose(); + } + } + + public void Invoke(object sender, global::System.ComponentModel.PropertyChangedEventArgs e) + { + using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(PropertyChangedEventHandler))); + var delegateToInvoke = agileDelegate ?? _nativeDelegate; + IntPtr ThisPtr = delegateToInvoke.ThisPtr; + var abiInvoke = Marshal.GetDelegateForFunctionPointer(delegateToInvoke.Vftbl.Invoke); + IObjectReference __sender = default; + IObjectReference __e = default; + try + { + __sender = MarshalInspectable.CreateMarshaler(sender); + __e = global::ABI.System.ComponentModel.PropertyChangedEventArgs.CreateMarshaler(e); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(abiInvoke(ThisPtr, MarshalInspectable.GetAbi(__sender), global::ABI.System.ComponentModel.PropertyChangedEventArgs.GetAbi(__e))); + } + finally + { + MarshalInspectable.DisposeMarshaler(__sender); + global::ABI.System.ComponentModel.PropertyChangedEventArgs.DisposeMarshaler(__e); + } + + } + } + + public static IntPtr FromManaged(global::System.ComponentModel.PropertyChangedEventHandler managedDelegate) => + managedDelegate is null ? IntPtr.Zero : CreateMarshaler(managedDelegate).GetRef(); + + public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper.DisposeMarshaler(value); + + public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper.DisposeAbi(abi); + + private static unsafe int Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e) + { + + + try + { + global::WinRT.ComWrappersSupport.MarshalDelegateInvoke(thisPtr, (global::System.ComponentModel.PropertyChangedEventHandler invoke) => + { + invoke(MarshalInspectable.FromAbi(sender), global::ABI.System.ComponentModel.PropertyChangedEventArgs.FromAbi(e)); + }); + } + catch (global::System.Exception __exception__) + { + global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); + return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); + } + return 0; + } + } +} diff --git a/WinRT.Runtime/Projections/SystemTypes.cs b/WinRT.Runtime/Projections/SystemTypes.net5.cs similarity index 99% rename from WinRT.Runtime/Projections/SystemTypes.cs rename to WinRT.Runtime/Projections/SystemTypes.net5.cs index 5bfe590fe..478aef4e4 100644 --- a/WinRT.Runtime/Projections/SystemTypes.cs +++ b/WinRT.Runtime/Projections/SystemTypes.net5.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; diff --git a/WinRT.Runtime/Projections/SystemTypes.netstandard2.0.cs b/WinRT.Runtime/Projections/SystemTypes.netstandard2.0.cs new file mode 100644 index 000000000..478aef4e4 --- /dev/null +++ b/WinRT.Runtime/Projections/SystemTypes.netstandard2.0.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +namespace ABI.System +{ + [StructLayout(LayoutKind.Sequential)] + public struct TimeSpan + { + // NOTE: both 'Windows.Foundation.TimeSpan.Duration' and 'System.TimeSpan.Ticks' are in units of 100ns + public long Duration; + + public struct Marshaler + { + public TimeSpan __abi; + } + + public static Marshaler CreateMarshaler(global::System.TimeSpan value) + { + return new Marshaler { __abi = new TimeSpan { Duration = value.Ticks } }; + } + + public static TimeSpan GetAbi(Marshaler m) => m.__abi; + + public static global::System.TimeSpan FromAbi(TimeSpan value) + { + return global::System.TimeSpan.FromTicks(value.Duration); + } + + public static unsafe void CopyAbi(Marshaler arg, IntPtr dest) => + *(TimeSpan*)dest.ToPointer() = GetAbi(arg); + + public static TimeSpan FromManaged(global::System.TimeSpan value) + { + return new TimeSpan { Duration = value.Ticks }; + } + + public static unsafe void CopyManaged(global::System.TimeSpan arg, IntPtr dest) => + *(TimeSpan*)dest.ToPointer() = FromManaged(arg); + + public static void DisposeMarshaler(Marshaler m) { } + public static void DisposeAbi(TimeSpan abi) { } + + public static string GetGuidSignature() + { + return "struct(Windows.Foundation.TimeSpan;i8)"; + } + } + + [StructLayout(LayoutKind.Sequential)] + public 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 + public long UniversalTime; + + public struct Marshaler + { + public DateTimeOffset __abi; + } + + public static Marshaler CreateMarshaler(global::System.DateTimeOffset value) + { + return new Marshaler { __abi = new DateTimeOffset { UniversalTime = value.ToFileTime() } }; + } + + public static DateTimeOffset GetAbi(Marshaler m) => m.__abi; + + public static global::System.DateTimeOffset FromAbi(DateTimeOffset value) + { + return global::System.DateTimeOffset.FromFileTime(value.UniversalTime); + } + + public static unsafe void CopyAbi(Marshaler arg, IntPtr dest) => + *(DateTimeOffset*)dest.ToPointer() = GetAbi(arg); + + public static DateTimeOffset FromManaged(global::System.DateTimeOffset value) + { + return new DateTimeOffset { UniversalTime = value.ToFileTime() }; + } + + public static unsafe void CopyManaged(global::System.DateTimeOffset arg, IntPtr dest) => + *(DateTimeOffset*)dest.ToPointer() = FromManaged(arg); + + public static void DisposeMarshaler(Marshaler m) { } + public static void DisposeAbi(DateTimeOffset abi) { } + + public static string GetGuidSignature() + { + return "struct(Windows.Foundation.DateTime;i8)"; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct Exception + { + public int hr; + + public struct Marshaler + { + public Exception __abi; + } + + public static Marshaler CreateMarshaler(global::System.Exception value) + { + return new Marshaler { __abi = new Exception { hr = value is object ? global::WinRT.ExceptionHelpers.GetHRForException(value) : 0 } }; + } + + public static Exception GetAbi(Marshaler m) => m.__abi; + + public static global::System.Exception FromAbi(Exception value) + { + return global::WinRT.ExceptionHelpers.GetExceptionForHR(value.hr); + } + + public static unsafe void CopyAbi(Marshaler arg, IntPtr dest) => + *(Exception*)dest.ToPointer() = GetAbi(arg); + + public static Exception FromManaged(global::System.Exception value) + { + return new Exception { hr = value is object ? global::WinRT.ExceptionHelpers.GetHRForException(value) : 0 }; + } + + public static unsafe void CopyManaged(global::System.Exception arg, IntPtr dest) => + *(Exception*)dest.ToPointer() = FromManaged(arg); + + public static void DisposeMarshaler(Marshaler m) { } + public static void DisposeAbi(Exception abi) { } + + public static string GetGuidSignature() + { + return "struct(Windows.Foundation.HResult;i4)"; + } + } +} diff --git a/WinRT.Runtime/Projections/Type.cs b/WinRT.Runtime/Projections/Type.net5.cs similarity index 99% rename from WinRT.Runtime/Projections/Type.cs rename to WinRT.Runtime/Projections/Type.net5.cs index 6424035cc..0abb587b7 100644 --- a/WinRT.Runtime/Projections/Type.cs +++ b/WinRT.Runtime/Projections/Type.net5.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using WinRT; diff --git a/WinRT.Runtime/Projections/Type.netstandard2.0.cs b/WinRT.Runtime/Projections/Type.netstandard2.0.cs new file mode 100644 index 000000000..0abb587b7 --- /dev/null +++ b/WinRT.Runtime/Projections/Type.netstandard2.0.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Text; +using WinRT; + +namespace ABI.System +{ + [WindowsRuntimeType("Windows.Foundation.UniversalApiContract")] + internal enum TypeKind : int + { + Primitive, + Metadata, + Custom + } + + public struct Type + { + private IntPtr Name; + private TypeKind Kind; + + public struct Marshaler + { + internal MarshalString Name; + internal TypeKind Kind; + + internal void Dispose() + { + MarshalString.DisposeMarshaler(Name); + } + } + + public static Marshaler CreateMarshaler(global::System.Type value) + { + TypeKind kind = TypeKind.Custom; + + if (value is object) + { + if (value.IsPrimitive) + { + kind = TypeKind.Primitive; + } + else if (value == typeof(object) || value == typeof(string) || value == typeof(Guid)) + { + kind = TypeKind.Metadata; + } + else if (Projections.IsTypeWindowsRuntimeType(value)) + { + kind = TypeKind.Metadata; + } + } + + return new Marshaler + { + Name = MarshalString.CreateMarshaler(TypeNameSupport.GetNameForType(value, TypeNameGenerationFlags.None)), + Kind = kind + }; + } + + public static Type GetAbi(Marshaler m) + { + return new Type + { + Name = MarshalString.GetAbi(m.Name), + Kind = m.Kind + }; + } + + public static global::System.Type FromAbi(Type value) + { + string name = MarshalString.FromAbi(value.Name); + if (string.IsNullOrEmpty(name)) + { + return null; + } + return TypeNameSupport.FindTypeByName(name.AsSpan()).type; + } + + public static unsafe void CopyAbi(Marshaler arg, IntPtr dest) => + *(Type*)dest.ToPointer() = GetAbi(arg); + + public static Type FromManaged(global::System.Type value) + { + return GetAbi(CreateMarshaler(value)); + } + + public static unsafe void CopyManaged(global::System.Type arg, IntPtr dest) => + *(Type*)dest.ToPointer() = FromManaged(arg); + + public static void DisposeMarshaler(Marshaler m) { m.Dispose(); } + public static void DisposeAbi(Type abi) { } + + public static string GetGuidSignature() + { + return "struct(Windows.UI.Xaml.Interop.TypeName;string;enum(Windows.UI.Xaml.Interop.TypeKind;i4))"; + } + } +} diff --git a/WinRT.Runtime/Projections/Uri.cs b/WinRT.Runtime/Projections/Uri.net5.cs similarity index 99% rename from WinRT.Runtime/Projections/Uri.cs rename to WinRT.Runtime/Projections/Uri.net5.cs index 69f3f3cab..096110126 100644 --- a/WinRT.Runtime/Projections/Uri.cs +++ b/WinRT.Runtime/Projections/Uri.net5.cs @@ -1,4 +1,4 @@ - + using System; using System.Runtime.InteropServices; using WinRT; diff --git a/WinRT.Runtime/Projections/Uri.netstandard2.0.cs b/WinRT.Runtime/Projections/Uri.netstandard2.0.cs new file mode 100644 index 000000000..096110126 --- /dev/null +++ b/WinRT.Runtime/Projections/Uri.netstandard2.0.cs @@ -0,0 +1,151 @@ + +using System; +using System.Runtime.InteropServices; +using WinRT; +using WinRT.Interop; + +namespace ABI.Windows.Foundation +{ + [Guid("9E365E57-48B2-4160-956F-C7385120BBFC")] + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct IUriRuntimeClassVftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + public IntPtr get_AbsoluteUri_0; + public IntPtr get_DisplayUri_1; + public IntPtr get_Domain_2; + public IntPtr get_Extension_3; + public IntPtr get_Fragment_4; + public IntPtr get_Host_5; + public IntPtr get_Password_6; + public IntPtr get_Path_7; + public IntPtr get_Query_8; + public IntPtr get_QueryParsed_9; + public void* _get_RawUri_10; + public delegate* stdcall get_RawUri_10 => (delegate* stdcall)_get_RawUri_10; + public IntPtr get_SchemeName_11; + public IntPtr get_UserName_12; + public IntPtr get_Port_13; + public IntPtr get_Suspicious_14; + public IntPtr Equals_15; + public IntPtr CombineUri_16; + } +} + +namespace ABI.System +{ + + [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] + [Guid("44A9796F-723E-4FDF-A218-033E75B0C084")] + internal class WinRTUriRuntimeClassFactory + { + [Guid("44A9796F-723E-4FDF-A218-033E75B0C084")] + [StructLayout(LayoutKind.Sequential)] + public unsafe struct Vftbl + { + internal IInspectable.Vftbl IInspectableVftbl; + private void* _CreateUri_0; + public delegate* stdcall CreateUri_0 => (delegate* stdcall)_CreateUri_0; + public IntPtr _CreateWithRelativeUri; + } + public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); + + public static implicit operator WinRTUriRuntimeClassFactory(IObjectReference obj) => (obj != null) ? new WinRTUriRuntimeClassFactory(obj) : null; + public static implicit operator WinRTUriRuntimeClassFactory(ObjectReference obj) => (obj != null) ? new WinRTUriRuntimeClassFactory(obj) : null; + protected readonly ObjectReference _obj; + public IntPtr ThisPtr => _obj.ThisPtr; + public ObjectReference AsInterface() => _obj.As(); + public A As() => _obj.AsType(); + public WinRTUriRuntimeClassFactory(IObjectReference obj) : this(obj.As()) { } + public WinRTUriRuntimeClassFactory(ObjectReference obj) + { + _obj = obj; + } + + public unsafe IObjectReference CreateUri(string uri) + { + MarshalString __uri = default; + IntPtr __retval = default; + try + { + __uri = MarshalString.CreateMarshaler(uri); + global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.CreateUri_0(ThisPtr, MarshalString.GetAbi(__uri), out __retval)); + return ObjectReference.Attach(ref __retval); + } + finally + { + MarshalString.DisposeMarshaler(__uri); + } + } + } + + + [StructLayout(LayoutKind.Sequential)] + public unsafe struct Uri + { + private static WeakLazy _uriActivationFactory = new WeakLazy(); + + private class ActivationFactory : BaseActivationFactory + { + public ActivationFactory() : base("Windows.Foundation", "Windows.Foundation.Uri") + { + } + } + + public static IObjectReference CreateMarshaler(global::System.Uri value) + { + if (value is null) + { + return null; + } + + WinRTUriRuntimeClassFactory factory = _uriActivationFactory.Value._As(); + return factory.CreateUri(value.OriginalString); + } + + public static IntPtr GetAbi(IObjectReference m) => m?.ThisPtr ?? IntPtr.Zero; + + public static global::System.Uri FromAbi(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + { + return null; + } + + using var uri = ObjectReference.FromAbi(ptr).As(); + IntPtr rawUri = IntPtr.Zero; + try + { + ExceptionHelpers.ThrowExceptionForHR(uri.Vftbl.get_RawUri_10(uri.ThisPtr, &rawUri)); + return new global::System.Uri(MarshalString.FromAbi(rawUri)); + } + finally + { + MarshalString.DisposeAbi(rawUri); + } + } + + public static unsafe void CopyManaged(global::System.Uri o, IntPtr dest) + { + using var objRef = CreateMarshaler(o); + *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero; + } + + public static IntPtr FromManaged(global::System.Uri value) + { + if (value is null) + { + return IntPtr.Zero; + } + return CreateMarshaler(value).GetRef(); + } + + public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } + public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } + + public static string GetGuidSignature() + { + return "rc(Windows.Foundation.Uri;{9e365e57-48b2-4160-956f-c7385120bbfc})"; + } + } +} diff --git a/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs b/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs index b71f9d664..3f05c5ce5 100644 --- a/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs +++ b/WinRT.Runtime/SingleInterfaceOptimizedObject.net5.cs @@ -42,15 +42,7 @@ bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfac { return true; } - return (this as IWinRTObject).IsInterfaceImplemented(interfaceType, throwIfNotImplemented); - } - - RuntimeTypeHandle IDynamicInterfaceCastable.GetInterfaceImplementation(RuntimeTypeHandle interfaceType) - { - var helperType = Type.GetTypeFromHandle(interfaceType).GetHelperType(); - if (helperType.IsInterface) - return helperType.TypeHandle; - return default; + return (this as IWinRTObject).IsInterfaceImplementedFallback(interfaceType, throwIfNotImplemented); } IObjectReference IWinRTObject.GetObjectReferenceForType(RuntimeTypeHandle interfaceType) @@ -59,7 +51,7 @@ IObjectReference IWinRTObject.GetObjectReferenceForType(RuntimeTypeHandle interf { return _obj; } - return (this as IWinRTObject).GetObjectReferenceForType(interfaceType); + return (this as IWinRTObject).GetObjectReferenceForTypeFallback(interfaceType); } } diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index 2f99093d1..b0f27182f 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -1156,15 +1156,14 @@ MarshalInspectable.DisposeAbi(ptr); else { w.write(R"( -public %() : this(%(ActivationFactory<%>.ActivateInstance<%.Vftbl>())) +public %() : this(%(ActivationFactory<%>.ActivateInstance())) { ComWrappersSupport.RegisterObjectForInterface(this, ThisPtr); } )", class_type.TypeName(), settings.netstandard_compat ? "new " + default_interface_name : "", - class_type.TypeName(), - default_interface_name); + class_type.TypeName()); } } @@ -2267,15 +2266,7 @@ event % %;)", set_simple_marshaler_type(m, type); break; case category::interface_type: - if (get_mapped_type(type.TypeNamespace(), type.TypeName()) && - type.TypeNamespace() == "Windows.Foundation.Collections") - { - m.marshaler_type = get_abi_type(); - } - else - { - m.marshaler_type = "MarshalInterface<" + m.param_type + ">"; - } + m.marshaler_type = "MarshalInterface<" + m.param_type + ">"; if (m.is_array()) { m.local_type = w.write_temp("MarshalInterfaceHelper<%>.MarshalerArray", m.param_type); @@ -3479,15 +3470,7 @@ remove => %.Unsubscribe(value); } break; case category::interface_type: - if (get_mapped_type(type.TypeNamespace(), type.TypeName()) && - type.TypeNamespace() == "Windows.Foundation.Collections") - { - m.marshaler_type = get_abi_type(); - } - else - { - m.marshaler_type = w.write_temp("MarshalInterface<%>", m.param_type); - } + m.marshaler_type = w.write_temp("MarshalInterface<%>", m.param_type); m.local_type = m.param_type; break; case category::class_type: @@ -4965,7 +4948,11 @@ private readonly AgileReference _agileReference = default; public NativeDelegateWrapper(ObjectReference nativeDelegate) { _nativeDelegate = nativeDelegate; +#if NETSTANDARD2_0 if (_nativeDelegate.TryAs(out var objRef) < 0) +#else +if (_nativeDelegate.TryAs(IAgileObject.IID, out var objRef) < 0) +#endif { _agileReference = new AgileReference(_nativeDelegate); } From ba117daf0d9ac4d7656d8514706dea01b561c286 Mon Sep 17 00:00:00 2001 From: UJJWAL CHADHA Date: Thu, 24 Sep 2020 00:50:03 -0400 Subject: [PATCH 20/23] Code cleanup --- .../Interop/IAgileReference.netstandard2.0.cs | 13 +- .../{EventHandler.net5.cs => EventHandler.cs} | 0 .../EventHandler.netstandard2.0.cs | 119 ---- .../{Geometry.net5.cs => Geometry.cs} | 0 .../Projections/Geometry.netstandard2.0.cs | 591 ------------------ ...t5.cs => NotifyCollectionChangedAction.cs} | 0 ...yCollectionChangedAction.netstandard2.0.cs | 11 - ...cs => NotifyCollectionChangedEventArgs.cs} | 0 ...llectionChangedEventArgs.netstandard2.0.cs | 242 ------- ...=> NotifyCollectionChangedEventHandler.cs} | 0 ...ctionChangedEventHandler.netstandard2.0.cs | 112 ---- .../{Nullable.net5.cs => Nullable.cs} | 0 .../Projections/Nullable.netstandard2.0.cs | 150 ----- .../{Numerics.net5.cs => Numerics.cs} | 0 .../Projections/Numerics.netstandard2.0.cs | 56 -- ...gs.net5.cs => PropertyChangedEventArgs.cs} | 0 ...PropertyChangedEventArgs.netstandard2.0.cs | 143 ----- ...net5.cs => PropertyChangedEventHandler.cs} | 0 ...pertyChangedEventHandler.netstandard2.0.cs | 113 ---- .../{SystemTypes.net5.cs => SystemTypes.cs} | 0 .../Projections/SystemTypes.netstandard2.0.cs | 136 ---- .../Projections/{Type.net5.cs => Type.cs} | 0 .../Projections/Type.netstandard2.0.cs | 97 --- .../Projections/{Uri.net5.cs => Uri.cs} | 0 .../Projections/Uri.netstandard2.0.cs | 151 ----- cswinrt/code_writers.h | 2 +- 26 files changed, 5 insertions(+), 1931 deletions(-) rename WinRT.Runtime/Projections/{EventHandler.net5.cs => EventHandler.cs} (100%) delete mode 100644 WinRT.Runtime/Projections/EventHandler.netstandard2.0.cs rename WinRT.Runtime/Projections/{Geometry.net5.cs => Geometry.cs} (100%) delete mode 100644 WinRT.Runtime/Projections/Geometry.netstandard2.0.cs rename WinRT.Runtime/Projections/{NotifyCollectionChangedAction.net5.cs => NotifyCollectionChangedAction.cs} (100%) delete mode 100644 WinRT.Runtime/Projections/NotifyCollectionChangedAction.netstandard2.0.cs rename WinRT.Runtime/Projections/{NotifyCollectionChangedEventArgs.net5.cs => NotifyCollectionChangedEventArgs.cs} (100%) delete mode 100644 WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.netstandard2.0.cs rename WinRT.Runtime/Projections/{NotifyCollectionChangedEventHandler.net5.cs => NotifyCollectionChangedEventHandler.cs} (100%) delete mode 100644 WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.netstandard2.0.cs rename WinRT.Runtime/Projections/{Nullable.net5.cs => Nullable.cs} (100%) delete mode 100644 WinRT.Runtime/Projections/Nullable.netstandard2.0.cs rename WinRT.Runtime/Projections/{Numerics.net5.cs => Numerics.cs} (100%) delete mode 100644 WinRT.Runtime/Projections/Numerics.netstandard2.0.cs rename WinRT.Runtime/Projections/{PropertyChangedEventArgs.net5.cs => PropertyChangedEventArgs.cs} (100%) delete mode 100644 WinRT.Runtime/Projections/PropertyChangedEventArgs.netstandard2.0.cs rename WinRT.Runtime/Projections/{PropertyChangedEventHandler.net5.cs => PropertyChangedEventHandler.cs} (100%) delete mode 100644 WinRT.Runtime/Projections/PropertyChangedEventHandler.netstandard2.0.cs rename WinRT.Runtime/Projections/{SystemTypes.net5.cs => SystemTypes.cs} (100%) delete mode 100644 WinRT.Runtime/Projections/SystemTypes.netstandard2.0.cs rename WinRT.Runtime/Projections/{Type.net5.cs => Type.cs} (100%) delete mode 100644 WinRT.Runtime/Projections/Type.netstandard2.0.cs rename WinRT.Runtime/Projections/{Uri.net5.cs => Uri.cs} (100%) delete mode 100644 WinRT.Runtime/Projections/Uri.netstandard2.0.cs diff --git a/WinRT.Runtime/Interop/IAgileReference.netstandard2.0.cs b/WinRT.Runtime/Interop/IAgileReference.netstandard2.0.cs index 686c56821..704d4cb4e 100644 --- a/WinRT.Runtime/Interop/IAgileReference.netstandard2.0.cs +++ b/WinRT.Runtime/Interop/IAgileReference.netstandard2.0.cs @@ -46,28 +46,23 @@ public struct Vftbl public static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; -#if NETSTANDARD2_0 + public delegate int ResolveDelegate(IntPtr thisPtr, Guid* riid, IntPtr* objectReference); private static readonly Delegate[] DelegateCache = new Delegate[1]; -#endif + static Vftbl() { AbiToProjectionVftable = new Vftbl { IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, -#if NETSTANDARD2_0 + _Resolve = Marshal.GetFunctionPointerForDelegate(DelegateCache[0] = new ResolveDelegate(Do_Abi_Resolve)).ToPointer(), -#else - _Resolve = (delegate*)&Do_Abi_Resolve -#endif + }; AbiToProjectionVftablePtr = Marshal.AllocHGlobal(Marshal.SizeOf()); Marshal.StructureToPtr(AbiToProjectionVftable, AbiToProjectionVftablePtr, false); } -#if !NETSTANDARD2_0 - [UnmanagedCallersOnly] -#endif private static int Do_Abi_Resolve(IntPtr thisPtr, Guid* riid, IntPtr* objectReference) { IObjectReference _objectReference = default; diff --git a/WinRT.Runtime/Projections/EventHandler.net5.cs b/WinRT.Runtime/Projections/EventHandler.cs similarity index 100% rename from WinRT.Runtime/Projections/EventHandler.net5.cs rename to WinRT.Runtime/Projections/EventHandler.cs diff --git a/WinRT.Runtime/Projections/EventHandler.netstandard2.0.cs b/WinRT.Runtime/Projections/EventHandler.netstandard2.0.cs deleted file mode 100644 index b1704ad5f..000000000 --- a/WinRT.Runtime/Projections/EventHandler.netstandard2.0.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Text; -using WinRT; -using WinRT.Interop; - -namespace ABI.System -{ - [Guid("9DE1C535-6AE1-11E0-84E1-18A905BCC53F"), EditorBrowsable(EditorBrowsableState.Never)] - public 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) }); - - private static readonly global::WinRT.Interop.IDelegateVftbl AbiToProjectionVftable; - public static readonly IntPtr AbiToProjectionVftablePtr; - - static EventHandler() - { - AbiInvokeDelegate = global::System.Delegate.CreateDelegate(Abi_Invoke_Type, typeof(EventHandler).GetMethod(nameof(Do_Abi_Invoke), BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(new global::System.Type[] { Marshaler.AbiType }) - ); - AbiToProjectionVftable = new global::WinRT.Interop.IDelegateVftbl - { - IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, - Invoke = Marshal.GetFunctionPointerForDelegate(AbiInvokeDelegate) - }; - var nativeVftbl = ComWrappersSupport.AllocateVtableMemory(typeof(EventHandler), Marshal.SizeOf()); - Marshal.StructureToPtr(AbiToProjectionVftable, nativeVftbl, false); - AbiToProjectionVftablePtr = nativeVftbl; - } - - public static global::System.Delegate AbiInvokeDelegate { get; } - - public static unsafe IObjectReference CreateMarshaler(global::System.EventHandler managedDelegate) => - managedDelegate is null ? null : ComWrappersSupport.CreateCCWForObject(managedDelegate).As(GuidGenerator.GetIID(typeof(EventHandler))); - - 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 = ObjectReference.FromAbi(nativeDelegate); - return (global::System.EventHandler)ComWrappersSupport.TryRegisterObjectForInterface(new global::System.EventHandler(new NativeDelegateWrapper(abiDelegate).Invoke), nativeDelegate); - } - - [global::WinRT.ObjectReferenceWrapper(nameof(_nativeDelegate))] - private class NativeDelegateWrapper - { - private readonly ObjectReference _nativeDelegate; - private readonly AgileReference _agileReference = default; - - public NativeDelegateWrapper(ObjectReference nativeDelegate) - { - _nativeDelegate = nativeDelegate; - if (_nativeDelegate.TryAs(out var objRef) < 0) - { - _agileReference = new AgileReference(_nativeDelegate); - } - else - { - objRef.Dispose(); - } - } - - public void Invoke(object sender, T args) - { - using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(EventHandler))); - var delegateToInvoke = agileDelegate ?? _nativeDelegate; - IntPtr ThisPtr = delegateToInvoke.ThisPtr; - var abiInvoke = Marshal.GetDelegateForFunctionPointer(delegateToInvoke.Vftbl.Invoke, Abi_Invoke_Type); - IObjectReference __sender = default; - object __args = default; - var __params = new object[] { ThisPtr, null, null }; - try - { - __sender = MarshalInspectable.CreateMarshaler(sender); - __params[1] = MarshalInspectable.GetAbi(__sender); - __args = Marshaler.CreateMarshaler(args); - __params[2] = Marshaler.GetAbi(__args); - abiInvoke.DynamicInvokeAbi(__params); - } - finally - { - MarshalInspectable.DisposeMarshaler(__sender); - Marshaler.DisposeMarshaler(__args); - } - - } - } - - public static IntPtr FromManaged(global::System.EventHandler managedDelegate) => - CreateMarshaler(managedDelegate)?.GetRef() ?? IntPtr.Zero; - - public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper>.DisposeMarshaler(value); - - public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper>.DisposeAbi(abi); - - private static unsafe int Do_Abi_Invoke(void* thisPtr, IntPtr sender, TAbi args) - { - try - { - global::WinRT.ComWrappersSupport.MarshalDelegateInvoke(new IntPtr(thisPtr), (global::System.Delegate invoke) => - { - invoke.DynamicInvoke(MarshalInspectable.FromAbi(sender), Marshaler.FromAbi(args)); - }); - } - catch (global::System.Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - } -} diff --git a/WinRT.Runtime/Projections/Geometry.net5.cs b/WinRT.Runtime/Projections/Geometry.cs similarity index 100% rename from WinRT.Runtime/Projections/Geometry.net5.cs rename to WinRT.Runtime/Projections/Geometry.cs diff --git a/WinRT.Runtime/Projections/Geometry.netstandard2.0.cs b/WinRT.Runtime/Projections/Geometry.netstandard2.0.cs deleted file mode 100644 index e50622a3b..000000000 --- a/WinRT.Runtime/Projections/Geometry.netstandard2.0.cs +++ /dev/null @@ -1,591 +0,0 @@ -using System; -using System.Globalization; -using System.Runtime.InteropServices; - -namespace Windows.Foundation -{ - internal class SR - { - public static string ArgumentOutOfRange_NeedNonNegNum = "Non-negative number required."; - } - - [global::WinRT.WindowsRuntimeType] - [StructLayout(LayoutKind.Sequential)] - public struct Point : IFormattable - { - public float _x; - public float _y; - - public Point(float x, float y) - { - _x = x; - _y = y; - } - - public Point(double x, double y) : this((float)x, (float)y) { } - - public double X - { - get { return _x; } - set { _x = (float)value; } - } - - public double Y - { - get { return _y; } - set { _y = (float)value; } - } - - public override string ToString() - { - return ConvertToString(null, null); - } - - public string ToString(IFormatProvider provider) - { - return ConvertToString(null, provider); - } - - string IFormattable.ToString(string format, IFormatProvider provider) - { - return ConvertToString(format, provider); - } - - private string ConvertToString(string format, IFormatProvider provider) - { - char separator = GetNumericListSeparator(provider); - return string.Format(provider, "{1:" + format + "}{0}{2:" + format + "}", separator, _x, _y); - } - - static char GetNumericListSeparator(IFormatProvider provider) - { - // If the decimal separator is a comma use ';' - char numericSeparator = ','; - var numberFormat = NumberFormatInfo.GetInstance(provider); - if ((numberFormat.NumberDecimalSeparator.Length > 0) && (numberFormat.NumberDecimalSeparator[0] == numericSeparator)) - { - numericSeparator = ';'; - } - - return numericSeparator; - } - - public static bool operator ==(Point point1, Point point2) - { - return point1._x == point2._x && point1._y == point2._y; - } - - public static bool operator !=(Point point1, Point point2) - { - return !(point1 == point2); - } - - public override bool Equals(object o) - { - return o is Point && this == (Point)o; - } - - public bool Equals(Point value) - { - return (this == value); - } - - public override int GetHashCode() - { - return X.GetHashCode() ^ Y.GetHashCode(); - } - } - - [global::WinRT.WindowsRuntimeType] - [StructLayout(LayoutKind.Sequential)] - public struct Rect : IFormattable - { - public float _x; - public float _y; - public float _width; - public float _height; - - private const double EmptyX = double.PositiveInfinity; - private const double EmptyY = double.PositiveInfinity; - private const double EmptyWidth = double.NegativeInfinity; - private const double EmptyHeight = double.NegativeInfinity; - - private static readonly Rect s_empty = CreateEmptyRect(); - - public Rect(float x, - float y, - float width, - float height) - { - if (width < 0) - throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum); - if (height < 0) - throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum); - - _x = x; - _y = y; - _width = width; - _height = height; - } - - public Rect(double x, - double y, - double width, - double height) : this((float)x, (float)y, (float)width, (float)height) { } - - public Rect(Point point1, - Point point2) - { - _x = Math.Min(point1._x, point2._x); - _y = Math.Min(point1._y, point2._y); - - _width = Math.Max(Math.Max(point1._x, point2._x) - _x, 0f); - _height = Math.Max(Math.Max(point1._y, point2._y) - _y, 0f); - } - - public Rect(Point location, Size size) - { - if (size.IsEmpty) - { - this = s_empty; - } - else - { - _x = location._x; - _y = location._y; - _width = size._width; - _height = size._height; - } - } - - public double X - { - get { return _x; } - set { _x = (float)value; } - } - - public double Y - { - get { return _y; } - set { _y = (float)value; } - } - - public double Width - { - get { return _width; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum); - - _width = (float)value; - } - } - - public double Height - { - get { return _height; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum); - - _height = (float)value; - } - } - - public double Left - { - get { return _x; } - } - - public double Top - { - get { return _y; } - } - - public double Right - { - get - { - if (IsEmpty) - { - return double.NegativeInfinity; - } - - return _x + _width; - } - } - - public double Bottom - { - get - { - if (IsEmpty) - { - return double.NegativeInfinity; - } - - return _y + _height; - } - } - - public static Rect Empty - { - get { return s_empty; } - } - - public bool IsEmpty - { - get { return _width < 0; } - } - - public bool Contains(Point point) - { - return ContainsInternal(point._x, point._y); - } - - public void Intersect(Rect rect) - { - if (!this.IntersectsWith(rect)) - { - this = s_empty; - } - else - { - double left = Math.Max(X, rect.X); - double top = Math.Max(Y, rect.Y); - - // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) - Width = Math.Max(Math.Min(X + Width, rect.X + rect.Width) - left, 0); - Height = Math.Max(Math.Min(Y + Height, rect.Y + rect.Height) - top, 0); - - X = left; - Y = top; - } - } - - public void Union(Rect rect) - { - if (IsEmpty) - { - this = rect; - } - else if (!rect.IsEmpty) - { - double left = Math.Min(Left, rect.Left); - double top = Math.Min(Top, rect.Top); - - - // We need this check so that the math does not result in NaN - if ((rect.Width == double.PositiveInfinity) || (Width == double.PositiveInfinity)) - { - Width = double.PositiveInfinity; - } - else - { - // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) - double maxRight = Math.Max(Right, rect.Right); - Width = Math.Max(maxRight - left, 0); - } - - // We need this check so that the math does not result in NaN - if ((rect.Height == double.PositiveInfinity) || (Height == double.PositiveInfinity)) - { - Height = double.PositiveInfinity; - } - else - { - // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) - double maxBottom = Math.Max(Bottom, rect.Bottom); - Height = Math.Max(maxBottom - top, 0); - } - - X = left; - Y = top; - } - } - - public void Union(Point point) - { - Union(new Rect(point, point)); - } - - private bool ContainsInternal(float x, float y) - { - return ((x >= _x) && (x - _width <= _x) && - (y >= _y) && (y - _height <= _y)); - } - - internal bool IntersectsWith(Rect rect) - { - if (_width < 0 || rect._width < 0) - { - return false; - } - - return (rect._x <= _x + _width) && - (rect._x + rect._width >= _x) && - (rect._y <= _y + _height) && - (rect._y + rect._height >= _y); - } - - private static Rect CreateEmptyRect() - { - Rect rect = default; - - rect._x = (float)EmptyX; - rect._y = (float)EmptyY; - - // the width and height properties prevent assignment of - // negative numbers so assign directly to the backing fields. - rect._width = (float)EmptyWidth; - rect._height = (float)EmptyHeight; - - return rect; - } - - public override string ToString() - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null /* format string */, null /* format provider */); - } - - public string ToString(IFormatProvider provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null /* format string */, provider); - } - - string IFormattable.ToString(string format, IFormatProvider provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(format, provider); - } - - - internal string ConvertToString(string format, IFormatProvider provider) - { - if (IsEmpty) - { - return "Empty."; - } - - // Helper to get the numeric list separator for a given culture. - char separator = TokenizerHelper.GetNumericListSeparator(provider); - return string.Format(provider, - "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}", - separator, - _x, - _y, - _width, - _height); - } - - public bool Equals(Rect value) - { - return (this == value); - } - - public static bool operator ==(Rect rect1, Rect rect2) - { - return rect1._x == rect2._x && - rect1._y == rect2._y && - rect1._width == rect2._width && - rect1._height == rect2._height; - } - - public static bool operator !=(Rect rect1, Rect rect2) - { - return !(rect1 == rect2); - } - - public override bool Equals(object o) - { - return o is Rect && this == (Rect)o; - } - - public override int GetHashCode() - { - // Perform field-by-field XOR of HashCodes - return X.GetHashCode() ^ - Y.GetHashCode() ^ - Width.GetHashCode() ^ - Height.GetHashCode(); - } - } - - [global::WinRT.WindowsRuntimeType] - [StructLayout(LayoutKind.Sequential)] - public struct Size - { - public float _width; - public float _height; - - private static readonly Size s_empty = CreateEmptySize(); - - public Size(float width, float height) - { - if (width < 0) - throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum); - if (height < 0) - throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum); - _width = width; - _height = height; - } - - public Size(double width, double height) : this((float)width, (float)height) { } - - public double Width - { - get { return _width; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum); - - _width = (float)value; - } - } - - public double Height - { - get { return _height; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum); - - _height = (float)value; - } - } - - public static Size Empty - { - get { return s_empty; } - } - - - public bool IsEmpty - { - get { return Width < 0; } - } - - private static Size CreateEmptySize() - { - Size size = default; - // We can't set these via the property setters because negatives widths - // are rejected in those APIs. - size._width = float.NegativeInfinity; - size._height = float.NegativeInfinity; - return size; - } - - public static bool operator ==(Size size1, Size size2) - { - return size1._width == size2._width && - size1._height == size2._height; - } - - public static bool operator !=(Size size1, Size size2) - { - return !(size1 == size2); - } - - public override bool Equals(object o) - { - return o is Size && Size.Equals(this, (Size)o); - } - - public bool Equals(Size value) - { - return Size.Equals(this, value); - } - - public override int GetHashCode() - { - if (IsEmpty) - { - return 0; - } - else - { - // Perform field-by-field XOR of HashCodes - return Width.GetHashCode() ^ - Height.GetHashCode(); - } - } - - private static bool Equals(Size size1, Size size2) - { - if (size1.IsEmpty) - { - return size2.IsEmpty; - } - else - { - return size1._width.Equals(size2._width) && - size1._height.Equals(size2._height); - } - } - - public override string ToString() - { - if (IsEmpty) - { - return "Empty"; - } - - return string.Format("{0},{1}", _width, _height); - } - } - - public static class TokenizerHelper - { - public static char GetNumericListSeparator(IFormatProvider provider) - { - char numericSeparator = ','; - - // Get the NumberFormatInfo out of the provider, if possible - // If the IFormatProvider doesn't not contain a NumberFormatInfo, then - // this method returns the current culture's NumberFormatInfo. - NumberFormatInfo numberFormat = NumberFormatInfo.GetInstance(provider); - - // Is the decimal separator is the same as the list separator? - // If so, we use the ";". - if ((numberFormat.NumberDecimalSeparator.Length > 0) && (numericSeparator == numberFormat.NumberDecimalSeparator[0])) - { - numericSeparator = ';'; - } - - return numericSeparator; - } - } -} - -namespace ABI.Windows.Foundation -{ - public static class Point - { - public static string GetGuidSignature() - { - return "struct(Windows.Foundation.Point;f4;f4)"; - } - } - - public static class Rect - { - public static string GetGuidSignature() - { - return "struct(Windows.Foundation.Rect;f4;f4;f4;f4)"; - } - } - - public static class Size - { - public static string GetGuidSignature() - { - return "struct(Windows.Foundation.Size;f4;f4)"; - } - } -} \ No newline at end of file diff --git a/WinRT.Runtime/Projections/NotifyCollectionChangedAction.net5.cs b/WinRT.Runtime/Projections/NotifyCollectionChangedAction.cs similarity index 100% rename from WinRT.Runtime/Projections/NotifyCollectionChangedAction.net5.cs rename to WinRT.Runtime/Projections/NotifyCollectionChangedAction.cs diff --git a/WinRT.Runtime/Projections/NotifyCollectionChangedAction.netstandard2.0.cs b/WinRT.Runtime/Projections/NotifyCollectionChangedAction.netstandard2.0.cs deleted file mode 100644 index 968335ce0..000000000 --- a/WinRT.Runtime/Projections/NotifyCollectionChangedAction.netstandard2.0.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace ABI.System.Collections.Specialized -{ - static class NotifyCollectionChangedAction - { - public static string GetGuidSignature() => "enum(Microsoft.UI.Xaml.Interop.NotifyCollectionChangedAction;i4)"; - } -} diff --git a/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.net5.cs b/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs similarity index 100% rename from WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.net5.cs rename to WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.cs diff --git a/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.netstandard2.0.cs b/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.netstandard2.0.cs deleted file mode 100644 index 868a1aa98..000000000 --- a/WinRT.Runtime/Projections/NotifyCollectionChangedEventArgs.netstandard2.0.cs +++ /dev/null @@ -1,242 +0,0 @@ -using ABI.Microsoft.UI.Xaml.Interop; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.InteropServices; -using System.Text; -using WinRT; -using WinRT.Interop; - -namespace ABI.Microsoft.UI.Xaml.Interop -{ - [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] - [Guid("DA049FF2-D2E0-5FE8-8C7B-F87F26060B6F")] - internal unsafe class INotifyCollectionChangedEventArgs - { - [Guid("DA049FF2-D2E0-5FE8-8C7B-F87F26060B6F")] - [StructLayout(LayoutKind.Sequential)] - public struct Vftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - private void* _get_Action_0; - public delegate* stdcall get_Action_0 => (delegate* stdcall)_get_Action_0; - private void* _get_NewItems_1; - public delegate* stdcall get_NewItems_1 => (delegate* stdcall)_get_NewItems_1; - private void* _get_OldItems_2; - public delegate* stdcall get_OldItems_2 => (delegate* stdcall)_get_OldItems_2; - private void* _get_NewStartingIndex_3; - public delegate* stdcall get_NewStartingIndex_3 => (delegate* stdcall)_get_NewStartingIndex_3; - private void* _get_OldStartingIndex_4; - public delegate* stdcall get_OldStartingIndex_4 => (delegate* stdcall)_get_OldStartingIndex_4; - } - internal static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); - - public static implicit operator INotifyCollectionChangedEventArgs(IObjectReference obj) => (obj != null) ? new INotifyCollectionChangedEventArgs(obj) : null; - protected readonly ObjectReference _obj; - public IObjectReference ObjRef { get => _obj; } - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - public INotifyCollectionChangedEventArgs(IObjectReference obj) : this(obj.As()) { } - internal INotifyCollectionChangedEventArgs(ObjectReference obj) - { - _obj = obj; - } - - public unsafe global::System.Collections.Specialized.NotifyCollectionChangedAction Action - { - get - { - global::System.Collections.Specialized.NotifyCollectionChangedAction __retval = default; - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_Action_0(ThisPtr, &__retval)); - return __retval; - } - } - - public unsafe global::System.Collections.IList NewItems - { - get - { - IntPtr __retval = default; - try - { - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_NewItems_1(ThisPtr, &__retval)); - return MarshalInterface.FromAbi(__retval); - } - finally - { - MarshalInterface.DisposeAbi(__retval); - } - } - } - - public unsafe int NewStartingIndex - { - get - { - int __retval = default; - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_NewStartingIndex_3(ThisPtr, &__retval)); - return __retval; - } - } - - public unsafe global::System.Collections.IList OldItems - { - get - { - IntPtr __retval = default; - try - { - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_OldItems_2(ThisPtr, &__retval)); - return MarshalInterface.FromAbi(__retval); - } - finally - { - MarshalInterface.DisposeAbi(__retval); - } - } - } - - public unsafe int OldStartingIndex - { - get - { - int __retval = default; - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.get_OldStartingIndex_4(ThisPtr, &__retval)); - return __retval; - } - } - } - - [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] - [Guid("5108EBA4-4892-5A20-8374-A96815E0FD27")] - internal unsafe class WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory - { - [Guid("5108EBA4-4892-5A20-8374-A96815E0FD27")] - [StructLayout(LayoutKind.Sequential)] - public struct Vftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - private void* _CreateInstanceWithAllParameters_0; - public delegate* stdcall CreateInstanceWithAllParameters_0 => (delegate* stdcall)_CreateInstanceWithAllParameters_0; - } - public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); - - public static implicit operator WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory(IObjectReference obj) => (obj != null) ? new WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory(obj) : null; - public static implicit operator WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory(ObjectReference obj) => (obj != null) ? new WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory(obj) : null; - protected readonly ObjectReference _obj; - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - public WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory(IObjectReference obj) : this(obj.As()) { } - public WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory(ObjectReference obj) - { - _obj = obj; - } - public unsafe IObjectReference CreateInstanceWithAllParameters(global::System.Collections.Specialized.NotifyCollectionChangedAction action, global::System.Collections.IList newItems, global::System.Collections.IList oldItems, int newIndex, int oldIndex, object baseInterface, out IObjectReference innerInterface) - { - IObjectReference __newItems = default; - IObjectReference __oldItems = default; - IObjectReference __baseInterface = default; - IntPtr __innerInterface = default; - IntPtr __retval = default; - try - { - __newItems = MarshalInterface.CreateMarshaler(newItems); - __oldItems = MarshalInterface.CreateMarshaler(oldItems); - __baseInterface = MarshalInspectable.CreateMarshaler(baseInterface); - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.CreateInstanceWithAllParameters_0(ThisPtr, action, MarshalInterface.GetAbi(__newItems), MarshalInterface.GetAbi(__oldItems), newIndex, oldIndex, MarshalInspectable.GetAbi(__baseInterface), out __innerInterface, out __retval)); - innerInterface = ObjectReference.FromAbi(__innerInterface); - return ObjectReference.FromAbi(__retval); - } - finally - { - MarshalInterface.DisposeMarshaler(__newItems); - MarshalInterface.DisposeMarshaler(__oldItems); - MarshalInspectable.DisposeMarshaler(__baseInterface); - MarshalInspectable.DisposeAbi(__innerInterface); - MarshalInspectable.DisposeAbi(__retval); - } - } - } -} - -namespace ABI.System.Collections.Specialized -{ - [EditorBrowsable(EditorBrowsableState.Never)] - [StructLayout(LayoutKind.Sequential)] - public struct NotifyCollectionChangedEventArgs - { - private static WeakLazy _propertyChangedArgsFactory = new WeakLazy(); - - private class ActivationFactory : BaseActivationFactory - { - public ActivationFactory() : base("Microsoft.UI.Xaml.Interop", "Microsoft.UI.Xaml.Interop.NotifyCollectionChangedEventArgs") - { - } - } - - public static IObjectReference CreateMarshaler(global::System.Collections.Specialized.NotifyCollectionChangedEventArgs value) - { - if (value is null) - { - return null; - } - - WinRTNotifyCollectionChangedEventArgsRuntimeClassFactory factory = _propertyChangedArgsFactory.Value._As(); - return factory.CreateInstanceWithAllParameters(value.Action, value.NewItems, value.OldItems, value.NewStartingIndex, value.OldStartingIndex, null, out _); - } - - public static IntPtr GetAbi(IObjectReference m) => m?.ThisPtr ?? IntPtr.Zero; - - public static global::System.Collections.Specialized.NotifyCollectionChangedEventArgs FromAbi(IntPtr ptr) - { - if (ptr == IntPtr.Zero) - { - return null; - } - - INotifyCollectionChangedEventArgs args = INotifyCollectionChangedEventArgs.FromAbi(ptr); - return CreateNotifyCollectionChangedEventArgs(args.Action, args.NewItems, args.OldItems, args.NewStartingIndex, args.OldStartingIndex); - } - - private static global::System.Collections.Specialized.NotifyCollectionChangedEventArgs CreateNotifyCollectionChangedEventArgs( - global::System.Collections.Specialized.NotifyCollectionChangedAction action, - global::System.Collections.IList newItems, - global::System.Collections.IList oldItems, - int newStartingIndex, - int oldStartingIndex) => - action switch - { - global::System.Collections.Specialized.NotifyCollectionChangedAction.Add => new global::System.Collections.Specialized.NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex), - global::System.Collections.Specialized.NotifyCollectionChangedAction.Remove => new global::System.Collections.Specialized.NotifyCollectionChangedEventArgs(action, oldItems, oldStartingIndex), - global::System.Collections.Specialized.NotifyCollectionChangedAction.Replace => new global::System.Collections.Specialized.NotifyCollectionChangedEventArgs(action, newItems, oldItems, newStartingIndex), - global::System.Collections.Specialized.NotifyCollectionChangedAction.Move => new global::System.Collections.Specialized.NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex, oldStartingIndex), - global::System.Collections.Specialized.NotifyCollectionChangedAction.Reset => new global::System.Collections.Specialized.NotifyCollectionChangedEventArgs(global::System.Collections.Specialized.NotifyCollectionChangedAction.Reset), - _ => throw new ArgumentException(), - }; - - public static unsafe void CopyManaged(global::System.Collections.Specialized.NotifyCollectionChangedEventArgs o, IntPtr dest) - { - using var objRef = CreateMarshaler(o); - *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero; - } - - public static IntPtr FromManaged(global::System.Collections.Specialized.NotifyCollectionChangedEventArgs value) - { - if (value is null) - { - return IntPtr.Zero; - } - return CreateMarshaler(value).GetRef(); - } - - public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } - - public static string GetGuidSignature() - { - return "rc(Microsoft.UI.Xaml.Interop.NotifyCollectionChangedEventArgs;{4cf68d33-e3f2-4964-b85e-945b4f7e2f21})"; - } - } -} diff --git a/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.net5.cs b/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs similarity index 100% rename from WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.net5.cs rename to WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.cs diff --git a/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.netstandard2.0.cs b/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.netstandard2.0.cs deleted file mode 100644 index 4448430f7..000000000 --- a/WinRT.Runtime/Projections/NotifyCollectionChangedEventHandler.netstandard2.0.cs +++ /dev/null @@ -1,112 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; -using WinRT; -using WinRT.Interop; - -namespace ABI.System.Collections.Specialized -{ - - [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - [Guid("8B0909DC-2005-5D93-BF8A-725F017BAA8D")] - public static class NotifyCollectionChangedEventHandler - { - private unsafe delegate int Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e); - - private static readonly global::WinRT.Interop.IDelegateVftbl AbiToProjectionVftable; - public static readonly IntPtr AbiToProjectionVftablePtr; - - static NotifyCollectionChangedEventHandler() - { - AbiInvokeDelegate = new Abi_Invoke(Do_Abi_Invoke); - AbiToProjectionVftable = new global::WinRT.Interop.IDelegateVftbl - { - IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, - Invoke = Marshal.GetFunctionPointerForDelegate(AbiInvokeDelegate) - }; - var nativeVftbl = ComWrappersSupport.AllocateVtableMemory(typeof(NotifyCollectionChangedEventHandler), Marshal.SizeOf()); - Marshal.StructureToPtr(AbiToProjectionVftable, nativeVftbl, false); - AbiToProjectionVftablePtr = nativeVftbl; - } - - public static global::System.Delegate AbiInvokeDelegate { get; } - - public static unsafe IObjectReference CreateMarshaler(global::System.Collections.Specialized.NotifyCollectionChangedEventHandler managedDelegate) => - managedDelegate is null ? null : ComWrappersSupport.CreateCCWForObject(managedDelegate).As(GuidGenerator.GetIID(typeof(NotifyCollectionChangedEventHandler))); - - public static IntPtr GetAbi(IObjectReference value) => MarshalInterfaceHelper.GetAbi(value); - - public static unsafe global::System.Collections.Specialized.NotifyCollectionChangedEventHandler FromAbi(IntPtr nativeDelegate) - { - var abiDelegate = ObjectReference.FromAbi(nativeDelegate); - 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))] - private class NativeDelegateWrapper - { - private readonly ObjectReference _nativeDelegate; - private readonly AgileReference _agileReference = default; - - public NativeDelegateWrapper(ObjectReference nativeDelegate) - { - _nativeDelegate = nativeDelegate; - if (_nativeDelegate.TryAs(out var objRef) < 0) - { - _agileReference = new AgileReference(_nativeDelegate); - } - else - { - objRef.Dispose(); - } - } - - public void Invoke(object sender, global::System.Collections.Specialized.NotifyCollectionChangedEventArgs e) - { - using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(NotifyCollectionChangedEventHandler))); - var delegateToInvoke = agileDelegate ?? _nativeDelegate; - IntPtr ThisPtr = delegateToInvoke.ThisPtr; - var abiInvoke = Marshal.GetDelegateForFunctionPointer(delegateToInvoke.Vftbl.Invoke); - IObjectReference __sender = default; - IObjectReference __e = default; - try - { - __sender = MarshalInspectable.CreateMarshaler(sender); - __e = global::ABI.System.Collections.Specialized.NotifyCollectionChangedEventArgs.CreateMarshaler(e); - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(abiInvoke(ThisPtr, MarshalInspectable.GetAbi(__sender), global::ABI.System.Collections.Specialized.NotifyCollectionChangedEventArgs.GetAbi(__e))); - } - finally - { - MarshalInspectable.DisposeMarshaler(__sender); - global::ABI.System.Collections.Specialized.NotifyCollectionChangedEventArgs.DisposeMarshaler(__e); - } - - } - } - - public static IntPtr FromManaged(global::System.Collections.Specialized.NotifyCollectionChangedEventHandler managedDelegate) => - managedDelegate is null ? IntPtr.Zero : CreateMarshaler(managedDelegate).GetRef(); - - public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper.DisposeMarshaler(value); - - public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper.DisposeAbi(abi); - - private static unsafe int Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e) - { - try - { - global::WinRT.ComWrappersSupport.MarshalDelegateInvoke(thisPtr, (global::System.Collections.Specialized.NotifyCollectionChangedEventHandler invoke) => - { - invoke(MarshalInspectable.FromAbi(sender), global::ABI.System.Collections.Specialized.NotifyCollectionChangedEventArgs.FromAbi(e)); - }); - } - catch (global::System.Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - } -} diff --git a/WinRT.Runtime/Projections/Nullable.net5.cs b/WinRT.Runtime/Projections/Nullable.cs similarity index 100% rename from WinRT.Runtime/Projections/Nullable.net5.cs rename to WinRT.Runtime/Projections/Nullable.cs diff --git a/WinRT.Runtime/Projections/Nullable.netstandard2.0.cs b/WinRT.Runtime/Projections/Nullable.netstandard2.0.cs deleted file mode 100644 index 517a21886..000000000 --- a/WinRT.Runtime/Projections/Nullable.netstandard2.0.cs +++ /dev/null @@ -1,150 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Text; -using WinRT; -using WinRT.Interop; - -namespace ABI.Windows.Foundation -{ - using System; - - internal static class BoxedValueIReferenceImpl - { - private static Nullable.Vftbl AbiToProjectionVftable; - public static IntPtr AbiToProjectionVftablePtr; - - static unsafe BoxedValueIReferenceImpl() - { - AbiToProjectionVftable = new Nullable.Vftbl - { - IInspectableVftbl = global::WinRT.IInspectable.Vftbl.AbiToProjectionVftable, - get_Value_0 = global::System.Delegate.CreateDelegate(Nullable.Vftbl.get_Value_0_Type, typeof(BoxedValueIReferenceImpl).GetMethod("Do_Abi_get_Value_0", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(Marshaler.AbiType)) - }; - var nativeVftbl = (IntPtr*)ComWrappersSupport.AllocateVtableMemory(typeof(BoxedValueIReferenceImpl), Marshal.SizeOf() + sizeof(IntPtr) * 1); - Marshal.StructureToPtr(AbiToProjectionVftable.IInspectableVftbl, (IntPtr)nativeVftbl, false); - nativeVftbl[6] = Marshal.GetFunctionPointerForDelegate(AbiToProjectionVftable.get_Value_0); - - AbiToProjectionVftablePtr = (IntPtr)nativeVftbl; - } - - private static unsafe int Do_Abi_get_Value_0(void* thisPtr, out TAbi __return_value__) - { - T ____return_value__ = default; - - __return_value__ = default; - - try - { - ____return_value__ = (T)global::WinRT.ComWrappersSupport.FindObject(new IntPtr(thisPtr)); - __return_value__ = (TAbi)Marshaler.FromManaged(____return_value__); - } - catch (global::System.Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - } -} - -namespace ABI.System -{ - [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] - [Guid("61C17706-2D65-11E0-9AE8-D48564015472")] - public class Nullable - { - public static IObjectReference CreateMarshaler(object value) - { - if (value is null) - { - return null; - } - return ComWrappersSupport.CreateCCWForObject(value).As(PIID); - } - - public static IntPtr GetAbi(IObjectReference m) => m?.ThisPtr ?? IntPtr.Zero; - - public static object FromAbi(IntPtr ptr) - { - if (ptr == IntPtr.Zero) - { - return null; - } - var vftblT = new Vftbl(ptr); - var wrapper = new Nullable(ObjectReference.FromAbi(ptr, vftblT)); - return wrapper.Value; - } - - public static unsafe void CopyManaged(object o, IntPtr dest) - { - using var objRef = CreateMarshaler(o); - *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero; - } - - public static IntPtr FromManaged(object value) - { - if (value is null) - { - return IntPtr.Zero; - } - return CreateMarshaler(value).GetRef(); - } - - public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } - - public static string GetGuidSignature() => GuidGenerator.GetSignature(typeof(Nullable)); - - [Guid("61C17706-2D65-11E0-9AE8-D48564015472")] - public struct Vftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - public global::System.Delegate get_Value_0; - public static Guid PIID = GuidGenerator.CreateIID(typeof(Nullable)); - public static readonly global::System.Type get_Value_0_Type = Expression.GetDelegateType(new global::System.Type[] { typeof(void*), Marshaler.AbiType.MakeByRefType(), typeof(int) }); - - internal unsafe Vftbl(IntPtr thisPtr) - { - var vftblPtr = Marshal.PtrToStructure(thisPtr); - var vftbl = (IntPtr*)vftblPtr.Vftbl; - IInspectableVftbl = Marshal.PtrToStructure(vftblPtr.Vftbl); - get_Value_0 = Marshal.GetDelegateForFunctionPointer(vftbl[6], get_Value_0_Type); - } - } - - public static Guid PIID = Vftbl.PIID; - - public static implicit operator Nullable(IObjectReference obj) => (obj != null) ? new Nullable(obj) : null; - public static implicit operator Nullable(ObjectReference obj) => (obj != null) ? new Nullable(obj) : null; - protected readonly ObjectReference _obj; - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - public Nullable(IObjectReference obj) : this(obj.As()) { } - public Nullable(ObjectReference obj) - { - _obj = obj; - } - - public unsafe T Value - { - get - { - var __params = new object[] { ThisPtr, null }; - try - { - _obj.Vftbl.get_Value_0.DynamicInvokeAbi(__params); - return Marshaler.FromAbi(__params[1]); - } - finally - { - Marshaler.DisposeAbi(__params[1]); - } - } - } - } -} diff --git a/WinRT.Runtime/Projections/Numerics.net5.cs b/WinRT.Runtime/Projections/Numerics.cs similarity index 100% rename from WinRT.Runtime/Projections/Numerics.net5.cs rename to WinRT.Runtime/Projections/Numerics.cs diff --git a/WinRT.Runtime/Projections/Numerics.netstandard2.0.cs b/WinRT.Runtime/Projections/Numerics.netstandard2.0.cs deleted file mode 100644 index 3b6ac2671..000000000 --- a/WinRT.Runtime/Projections/Numerics.netstandard2.0.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; - -namespace ABI.System.Numerics -{ - [StructLayout(LayoutKind.Sequential)] - public struct Matrix3x2 - { - public static string GetGuidSignature() => - "struct(Windows.Foundation.Numerics.Matrix3x2;f4;f4;f4;f4;f4;f4)"; - } - - [StructLayout(LayoutKind.Sequential)] - public 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 - { - public static string GetGuidSignature() => - "struct(Windows.Foundation.Numerics.Plane;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);f4)"; - } - - [StructLayout(LayoutKind.Sequential)] - public struct Quaternion - { - public static string GetGuidSignature() => - "struct(Windows.Foundation.Numerics.Quaternion;f4;f4;f4;f4)"; - } - - [StructLayout(LayoutKind.Sequential)] - public struct Vector2 - { - public static string GetGuidSignature() => - "struct(Windows.Foundation.Numerics.Vector2;f4;f4)"; - } - - [StructLayout(LayoutKind.Sequential)] - public struct Vector3 - { - public static string GetGuidSignature() => - "struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4)"; - } - - [StructLayout(LayoutKind.Sequential)] - public struct Vector4 - { - public static string GetGuidSignature() => - "struct(Windows.Foundation.Numerics.Vector4;f4;f4;f4;f4)"; - } -} diff --git a/WinRT.Runtime/Projections/PropertyChangedEventArgs.net5.cs b/WinRT.Runtime/Projections/PropertyChangedEventArgs.cs similarity index 100% rename from WinRT.Runtime/Projections/PropertyChangedEventArgs.net5.cs rename to WinRT.Runtime/Projections/PropertyChangedEventArgs.cs diff --git a/WinRT.Runtime/Projections/PropertyChangedEventArgs.netstandard2.0.cs b/WinRT.Runtime/Projections/PropertyChangedEventArgs.netstandard2.0.cs deleted file mode 100644 index 9809aefe2..000000000 --- a/WinRT.Runtime/Projections/PropertyChangedEventArgs.netstandard2.0.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.InteropServices; -using System.Text; -using WinRT; -using WinRT.Interop; - -namespace ABI.Microsoft.UI.Xaml.Data -{ - [Guid("63D0C952-396B-54F4-AF8C-BA8724A427BF")] - [StructLayout(LayoutKind.Sequential)] - internal unsafe struct IPropertyChangedEventArgsVftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - private void* _get_PropertyName_0; - public delegate* stdcall get_PropertyName_0 => (delegate* stdcall)_get_PropertyName_0; - } - - - [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] - [Guid("7C0C27A8-0B41-5070-B160-FC9AE960A36C")] - internal unsafe class WinRTPropertyChangedEventArgsRuntimeClassFactory - { - [Guid("7C0C27A8-0B41-5070-B160-FC9AE960A36C")] - [StructLayout(LayoutKind.Sequential)] - public struct Vftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - private void* _CreateInstance_0; - public delegate* stdcall CreateInstance_0 => (delegate* stdcall)_CreateInstance_0; - } - public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); - - public static implicit operator WinRTPropertyChangedEventArgsRuntimeClassFactory(IObjectReference obj) => (obj != null) ? new WinRTPropertyChangedEventArgsRuntimeClassFactory(obj) : null; - public static implicit operator WinRTPropertyChangedEventArgsRuntimeClassFactory(ObjectReference obj) => (obj != null) ? new WinRTPropertyChangedEventArgsRuntimeClassFactory(obj) : null; - protected readonly ObjectReference _obj; - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - public WinRTPropertyChangedEventArgsRuntimeClassFactory(IObjectReference obj) : this(obj.As()) { } - public WinRTPropertyChangedEventArgsRuntimeClassFactory(ObjectReference obj) - { - _obj = obj; - } - - public unsafe IObjectReference CreateInstance(string name, object baseInterface, out IObjectReference innerInterface) - { - MarshalString __name = default; - IObjectReference __baseInterface = default; - IntPtr __innerInterface = default; - IntPtr __retval = default; - try - { - __name = MarshalString.CreateMarshaler(name); - __baseInterface = MarshalInspectable.CreateMarshaler(baseInterface); - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.CreateInstance_0(ThisPtr, MarshalString.GetAbi(__name), MarshalInspectable.GetAbi(__baseInterface), &__innerInterface, &__retval)); - innerInterface = ObjectReference.FromAbi(__innerInterface); - return ObjectReference.Attach(ref __retval); - } - finally - { - MarshalString.DisposeMarshaler(__name); - MarshalInspectable.DisposeMarshaler(__baseInterface); - MarshalInspectable.DisposeAbi(__innerInterface); - MarshalInspectable.DisposeAbi(__retval); - } - } - } -} - -namespace ABI.System.ComponentModel -{ - [EditorBrowsable(EditorBrowsableState.Never)] - [StructLayout(LayoutKind.Sequential)] - public unsafe struct PropertyChangedEventArgs - { - private static WeakLazy _propertyChangedArgsFactory = new WeakLazy(); - - private class ActivationFactory : BaseActivationFactory - { - public ActivationFactory() : base("Microsoft.UI.Xaml.Data", "Microsoft.UI.Xaml.Data.PropertyChangedEventArgs") - { - } - } - - public static IObjectReference CreateMarshaler(global::System.ComponentModel.PropertyChangedEventArgs value) - { - if (value is null) - { - return null; - } - - ABI.Microsoft.UI.Xaml.Data.WinRTPropertyChangedEventArgsRuntimeClassFactory factory = _propertyChangedArgsFactory.Value._As(); - return factory.CreateInstance(value.PropertyName, null, out _); - } - - public static IntPtr GetAbi(IObjectReference m) => m?.ThisPtr ?? IntPtr.Zero; - - public static global::System.ComponentModel.PropertyChangedEventArgs FromAbi(IntPtr ptr) - { - if (ptr == IntPtr.Zero) - { - return null; - } - - using var args = ObjectReference.FromAbi(ptr); - IntPtr propertyName = IntPtr.Zero; - try - { - ExceptionHelpers.ThrowExceptionForHR(args.Vftbl.get_PropertyName_0(args.ThisPtr, &propertyName)); - return new global::System.ComponentModel.PropertyChangedEventArgs(MarshalString.FromAbi(propertyName)); - } - finally - { - MarshalString.DisposeAbi(propertyName); - } - } - - public static unsafe void CopyManaged(global::System.ComponentModel.PropertyChangedEventArgs o, IntPtr dest) - { - using var objRef = CreateMarshaler(o); - *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero; - } - - public static IntPtr FromManaged(global::System.ComponentModel.PropertyChangedEventArgs value) - { - if (value is null) - { - return IntPtr.Zero; - } - return CreateMarshaler(value).GetRef(); - } - - public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } - - public static string GetGuidSignature() - { - return "rc(Microsoft.UI.Xaml.Data.NotifyPropertyChangedEventArgs;{4f33a9a0-5cf4-47a4-b16f-d7faaf17457e})"; - } - } -} diff --git a/WinRT.Runtime/Projections/PropertyChangedEventHandler.net5.cs b/WinRT.Runtime/Projections/PropertyChangedEventHandler.cs similarity index 100% rename from WinRT.Runtime/Projections/PropertyChangedEventHandler.net5.cs rename to WinRT.Runtime/Projections/PropertyChangedEventHandler.cs diff --git a/WinRT.Runtime/Projections/PropertyChangedEventHandler.netstandard2.0.cs b/WinRT.Runtime/Projections/PropertyChangedEventHandler.netstandard2.0.cs deleted file mode 100644 index faf539856..000000000 --- a/WinRT.Runtime/Projections/PropertyChangedEventHandler.netstandard2.0.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; -using WinRT; -using WinRT.Interop; - -namespace ABI.System.ComponentModel -{ - [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - [Guid("E3DE52F6-1E32-5DA6-BB2D-B5B6096C962D")] - public static class PropertyChangedEventHandler - { - private unsafe delegate int Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e); - - private static readonly global::WinRT.Interop.IDelegateVftbl AbiToProjectionVftable; - public static readonly IntPtr AbiToProjectionVftablePtr; - - static PropertyChangedEventHandler() - { - AbiInvokeDelegate = new Abi_Invoke(Do_Abi_Invoke); - AbiToProjectionVftable = new global::WinRT.Interop.IDelegateVftbl - { - IUnknownVftbl = global::WinRT.Interop.IUnknownVftbl.AbiToProjectionVftbl, - Invoke = Marshal.GetFunctionPointerForDelegate(AbiInvokeDelegate) - }; - var nativeVftbl = ComWrappersSupport.AllocateVtableMemory(typeof(PropertyChangedEventHandler), Marshal.SizeOf()); - Marshal.StructureToPtr(AbiToProjectionVftable, nativeVftbl, false); - AbiToProjectionVftablePtr = nativeVftbl; - } - - public static global::System.Delegate AbiInvokeDelegate { get; } - - public static unsafe IObjectReference CreateMarshaler(global::System.ComponentModel.PropertyChangedEventHandler managedDelegate) => - managedDelegate is null ? null : ComWrappersSupport.CreateCCWForObject(managedDelegate).As(GuidGenerator.GetIID(typeof(PropertyChangedEventHandler))); - - public static IntPtr GetAbi(IObjectReference value) => MarshalInterfaceHelper.GetAbi(value); - - public static unsafe global::System.ComponentModel.PropertyChangedEventHandler FromAbi(IntPtr nativeDelegate) - { - var abiDelegate = ObjectReference.FromAbi(nativeDelegate); - 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))] - private class NativeDelegateWrapper - { - private readonly ObjectReference _nativeDelegate; - private readonly AgileReference _agileReference = default; - - public NativeDelegateWrapper(ObjectReference nativeDelegate) - { - _nativeDelegate = nativeDelegate; - if (_nativeDelegate.TryAs(out var objRef) < 0) - { - _agileReference = new AgileReference(_nativeDelegate); - } - else - { - objRef.Dispose(); - } - } - - public void Invoke(object sender, global::System.ComponentModel.PropertyChangedEventArgs e) - { - using var agileDelegate = _agileReference?.Get()?.As(GuidGenerator.GetIID(typeof(PropertyChangedEventHandler))); - var delegateToInvoke = agileDelegate ?? _nativeDelegate; - IntPtr ThisPtr = delegateToInvoke.ThisPtr; - var abiInvoke = Marshal.GetDelegateForFunctionPointer(delegateToInvoke.Vftbl.Invoke); - IObjectReference __sender = default; - IObjectReference __e = default; - try - { - __sender = MarshalInspectable.CreateMarshaler(sender); - __e = global::ABI.System.ComponentModel.PropertyChangedEventArgs.CreateMarshaler(e); - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(abiInvoke(ThisPtr, MarshalInspectable.GetAbi(__sender), global::ABI.System.ComponentModel.PropertyChangedEventArgs.GetAbi(__e))); - } - finally - { - MarshalInspectable.DisposeMarshaler(__sender); - global::ABI.System.ComponentModel.PropertyChangedEventArgs.DisposeMarshaler(__e); - } - - } - } - - public static IntPtr FromManaged(global::System.ComponentModel.PropertyChangedEventHandler managedDelegate) => - managedDelegate is null ? IntPtr.Zero : CreateMarshaler(managedDelegate).GetRef(); - - public static void DisposeMarshaler(IObjectReference value) => MarshalInterfaceHelper.DisposeMarshaler(value); - - public static void DisposeAbi(IntPtr abi) => MarshalInterfaceHelper.DisposeAbi(abi); - - private static unsafe int Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e) - { - - - try - { - global::WinRT.ComWrappersSupport.MarshalDelegateInvoke(thisPtr, (global::System.ComponentModel.PropertyChangedEventHandler invoke) => - { - invoke(MarshalInspectable.FromAbi(sender), global::ABI.System.ComponentModel.PropertyChangedEventArgs.FromAbi(e)); - }); - } - catch (global::System.Exception __exception__) - { - global::WinRT.ExceptionHelpers.SetErrorInfo(__exception__); - return global::WinRT.ExceptionHelpers.GetHRForException(__exception__); - } - return 0; - } - } -} diff --git a/WinRT.Runtime/Projections/SystemTypes.net5.cs b/WinRT.Runtime/Projections/SystemTypes.cs similarity index 100% rename from WinRT.Runtime/Projections/SystemTypes.net5.cs rename to WinRT.Runtime/Projections/SystemTypes.cs diff --git a/WinRT.Runtime/Projections/SystemTypes.netstandard2.0.cs b/WinRT.Runtime/Projections/SystemTypes.netstandard2.0.cs deleted file mode 100644 index 478aef4e4..000000000 --- a/WinRT.Runtime/Projections/SystemTypes.netstandard2.0.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; - -namespace ABI.System -{ - [StructLayout(LayoutKind.Sequential)] - public struct TimeSpan - { - // NOTE: both 'Windows.Foundation.TimeSpan.Duration' and 'System.TimeSpan.Ticks' are in units of 100ns - public long Duration; - - public struct Marshaler - { - public TimeSpan __abi; - } - - public static Marshaler CreateMarshaler(global::System.TimeSpan value) - { - return new Marshaler { __abi = new TimeSpan { Duration = value.Ticks } }; - } - - public static TimeSpan GetAbi(Marshaler m) => m.__abi; - - public static global::System.TimeSpan FromAbi(TimeSpan value) - { - return global::System.TimeSpan.FromTicks(value.Duration); - } - - public static unsafe void CopyAbi(Marshaler arg, IntPtr dest) => - *(TimeSpan*)dest.ToPointer() = GetAbi(arg); - - public static TimeSpan FromManaged(global::System.TimeSpan value) - { - return new TimeSpan { Duration = value.Ticks }; - } - - public static unsafe void CopyManaged(global::System.TimeSpan arg, IntPtr dest) => - *(TimeSpan*)dest.ToPointer() = FromManaged(arg); - - public static void DisposeMarshaler(Marshaler m) { } - public static void DisposeAbi(TimeSpan abi) { } - - public static string GetGuidSignature() - { - return "struct(Windows.Foundation.TimeSpan;i8)"; - } - } - - [StructLayout(LayoutKind.Sequential)] - public 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 - public long UniversalTime; - - public struct Marshaler - { - public DateTimeOffset __abi; - } - - public static Marshaler CreateMarshaler(global::System.DateTimeOffset value) - { - return new Marshaler { __abi = new DateTimeOffset { UniversalTime = value.ToFileTime() } }; - } - - public static DateTimeOffset GetAbi(Marshaler m) => m.__abi; - - public static global::System.DateTimeOffset FromAbi(DateTimeOffset value) - { - return global::System.DateTimeOffset.FromFileTime(value.UniversalTime); - } - - public static unsafe void CopyAbi(Marshaler arg, IntPtr dest) => - *(DateTimeOffset*)dest.ToPointer() = GetAbi(arg); - - public static DateTimeOffset FromManaged(global::System.DateTimeOffset value) - { - return new DateTimeOffset { UniversalTime = value.ToFileTime() }; - } - - public static unsafe void CopyManaged(global::System.DateTimeOffset arg, IntPtr dest) => - *(DateTimeOffset*)dest.ToPointer() = FromManaged(arg); - - public static void DisposeMarshaler(Marshaler m) { } - public static void DisposeAbi(DateTimeOffset abi) { } - - public static string GetGuidSignature() - { - return "struct(Windows.Foundation.DateTime;i8)"; - } - } - - [StructLayout(LayoutKind.Sequential)] - public struct Exception - { - public int hr; - - public struct Marshaler - { - public Exception __abi; - } - - public static Marshaler CreateMarshaler(global::System.Exception value) - { - return new Marshaler { __abi = new Exception { hr = value is object ? global::WinRT.ExceptionHelpers.GetHRForException(value) : 0 } }; - } - - public static Exception GetAbi(Marshaler m) => m.__abi; - - public static global::System.Exception FromAbi(Exception value) - { - return global::WinRT.ExceptionHelpers.GetExceptionForHR(value.hr); - } - - public static unsafe void CopyAbi(Marshaler arg, IntPtr dest) => - *(Exception*)dest.ToPointer() = GetAbi(arg); - - public static Exception FromManaged(global::System.Exception value) - { - return new Exception { hr = value is object ? global::WinRT.ExceptionHelpers.GetHRForException(value) : 0 }; - } - - public static unsafe void CopyManaged(global::System.Exception arg, IntPtr dest) => - *(Exception*)dest.ToPointer() = FromManaged(arg); - - public static void DisposeMarshaler(Marshaler m) { } - public static void DisposeAbi(Exception abi) { } - - public static string GetGuidSignature() - { - return "struct(Windows.Foundation.HResult;i4)"; - } - } -} diff --git a/WinRT.Runtime/Projections/Type.net5.cs b/WinRT.Runtime/Projections/Type.cs similarity index 100% rename from WinRT.Runtime/Projections/Type.net5.cs rename to WinRT.Runtime/Projections/Type.cs diff --git a/WinRT.Runtime/Projections/Type.netstandard2.0.cs b/WinRT.Runtime/Projections/Type.netstandard2.0.cs deleted file mode 100644 index 0abb587b7..000000000 --- a/WinRT.Runtime/Projections/Type.netstandard2.0.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WinRT; - -namespace ABI.System -{ - [WindowsRuntimeType("Windows.Foundation.UniversalApiContract")] - internal enum TypeKind : int - { - Primitive, - Metadata, - Custom - } - - public struct Type - { - private IntPtr Name; - private TypeKind Kind; - - public struct Marshaler - { - internal MarshalString Name; - internal TypeKind Kind; - - internal void Dispose() - { - MarshalString.DisposeMarshaler(Name); - } - } - - public static Marshaler CreateMarshaler(global::System.Type value) - { - TypeKind kind = TypeKind.Custom; - - if (value is object) - { - if (value.IsPrimitive) - { - kind = TypeKind.Primitive; - } - else if (value == typeof(object) || value == typeof(string) || value == typeof(Guid)) - { - kind = TypeKind.Metadata; - } - else if (Projections.IsTypeWindowsRuntimeType(value)) - { - kind = TypeKind.Metadata; - } - } - - return new Marshaler - { - Name = MarshalString.CreateMarshaler(TypeNameSupport.GetNameForType(value, TypeNameGenerationFlags.None)), - Kind = kind - }; - } - - public static Type GetAbi(Marshaler m) - { - return new Type - { - Name = MarshalString.GetAbi(m.Name), - Kind = m.Kind - }; - } - - public static global::System.Type FromAbi(Type value) - { - string name = MarshalString.FromAbi(value.Name); - if (string.IsNullOrEmpty(name)) - { - return null; - } - return TypeNameSupport.FindTypeByName(name.AsSpan()).type; - } - - public static unsafe void CopyAbi(Marshaler arg, IntPtr dest) => - *(Type*)dest.ToPointer() = GetAbi(arg); - - public static Type FromManaged(global::System.Type value) - { - return GetAbi(CreateMarshaler(value)); - } - - public static unsafe void CopyManaged(global::System.Type arg, IntPtr dest) => - *(Type*)dest.ToPointer() = FromManaged(arg); - - public static void DisposeMarshaler(Marshaler m) { m.Dispose(); } - public static void DisposeAbi(Type abi) { } - - public static string GetGuidSignature() - { - return "struct(Windows.UI.Xaml.Interop.TypeName;string;enum(Windows.UI.Xaml.Interop.TypeKind;i4))"; - } - } -} diff --git a/WinRT.Runtime/Projections/Uri.net5.cs b/WinRT.Runtime/Projections/Uri.cs similarity index 100% rename from WinRT.Runtime/Projections/Uri.net5.cs rename to WinRT.Runtime/Projections/Uri.cs diff --git a/WinRT.Runtime/Projections/Uri.netstandard2.0.cs b/WinRT.Runtime/Projections/Uri.netstandard2.0.cs deleted file mode 100644 index 096110126..000000000 --- a/WinRT.Runtime/Projections/Uri.netstandard2.0.cs +++ /dev/null @@ -1,151 +0,0 @@ - -using System; -using System.Runtime.InteropServices; -using WinRT; -using WinRT.Interop; - -namespace ABI.Windows.Foundation -{ - [Guid("9E365E57-48B2-4160-956F-C7385120BBFC")] - [StructLayout(LayoutKind.Sequential)] - internal unsafe struct IUriRuntimeClassVftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - public IntPtr get_AbsoluteUri_0; - public IntPtr get_DisplayUri_1; - public IntPtr get_Domain_2; - public IntPtr get_Extension_3; - public IntPtr get_Fragment_4; - public IntPtr get_Host_5; - public IntPtr get_Password_6; - public IntPtr get_Path_7; - public IntPtr get_Query_8; - public IntPtr get_QueryParsed_9; - public void* _get_RawUri_10; - public delegate* stdcall get_RawUri_10 => (delegate* stdcall)_get_RawUri_10; - public IntPtr get_SchemeName_11; - public IntPtr get_UserName_12; - public IntPtr get_Port_13; - public IntPtr get_Suspicious_14; - public IntPtr Equals_15; - public IntPtr CombineUri_16; - } -} - -namespace ABI.System -{ - - [global::WinRT.ObjectReferenceWrapper(nameof(_obj))] - [Guid("44A9796F-723E-4FDF-A218-033E75B0C084")] - internal class WinRTUriRuntimeClassFactory - { - [Guid("44A9796F-723E-4FDF-A218-033E75B0C084")] - [StructLayout(LayoutKind.Sequential)] - public unsafe struct Vftbl - { - internal IInspectable.Vftbl IInspectableVftbl; - private void* _CreateUri_0; - public delegate* stdcall CreateUri_0 => (delegate* stdcall)_CreateUri_0; - public IntPtr _CreateWithRelativeUri; - } - public static ObjectReference FromAbi(IntPtr thisPtr) => ObjectReference.FromAbi(thisPtr); - - public static implicit operator WinRTUriRuntimeClassFactory(IObjectReference obj) => (obj != null) ? new WinRTUriRuntimeClassFactory(obj) : null; - public static implicit operator WinRTUriRuntimeClassFactory(ObjectReference obj) => (obj != null) ? new WinRTUriRuntimeClassFactory(obj) : null; - protected readonly ObjectReference _obj; - public IntPtr ThisPtr => _obj.ThisPtr; - public ObjectReference AsInterface() => _obj.As(); - public A As() => _obj.AsType(); - public WinRTUriRuntimeClassFactory(IObjectReference obj) : this(obj.As()) { } - public WinRTUriRuntimeClassFactory(ObjectReference obj) - { - _obj = obj; - } - - public unsafe IObjectReference CreateUri(string uri) - { - MarshalString __uri = default; - IntPtr __retval = default; - try - { - __uri = MarshalString.CreateMarshaler(uri); - global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.CreateUri_0(ThisPtr, MarshalString.GetAbi(__uri), out __retval)); - return ObjectReference.Attach(ref __retval); - } - finally - { - MarshalString.DisposeMarshaler(__uri); - } - } - } - - - [StructLayout(LayoutKind.Sequential)] - public unsafe struct Uri - { - private static WeakLazy _uriActivationFactory = new WeakLazy(); - - private class ActivationFactory : BaseActivationFactory - { - public ActivationFactory() : base("Windows.Foundation", "Windows.Foundation.Uri") - { - } - } - - public static IObjectReference CreateMarshaler(global::System.Uri value) - { - if (value is null) - { - return null; - } - - WinRTUriRuntimeClassFactory factory = _uriActivationFactory.Value._As(); - return factory.CreateUri(value.OriginalString); - } - - public static IntPtr GetAbi(IObjectReference m) => m?.ThisPtr ?? IntPtr.Zero; - - public static global::System.Uri FromAbi(IntPtr ptr) - { - if (ptr == IntPtr.Zero) - { - return null; - } - - using var uri = ObjectReference.FromAbi(ptr).As(); - IntPtr rawUri = IntPtr.Zero; - try - { - ExceptionHelpers.ThrowExceptionForHR(uri.Vftbl.get_RawUri_10(uri.ThisPtr, &rawUri)); - return new global::System.Uri(MarshalString.FromAbi(rawUri)); - } - finally - { - MarshalString.DisposeAbi(rawUri); - } - } - - public static unsafe void CopyManaged(global::System.Uri o, IntPtr dest) - { - using var objRef = CreateMarshaler(o); - *(IntPtr*)dest.ToPointer() = objRef?.GetRef() ?? IntPtr.Zero; - } - - public static IntPtr FromManaged(global::System.Uri value) - { - if (value is null) - { - return IntPtr.Zero; - } - return CreateMarshaler(value).GetRef(); - } - - public static void DisposeMarshaler(IObjectReference m) { m?.Dispose(); } - public static void DisposeAbi(IntPtr abi) { using var objRef = ObjectReference.Attach(ref abi); } - - public static string GetGuidSignature() - { - return "rc(Windows.Foundation.Uri;{9e365e57-48b2-4160-956f-c7385120bbfc})"; - } - } -} diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index b0f27182f..73bf262fb 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -4466,7 +4466,7 @@ public static class % { XLANG_ASSERT(get_category(type) == category::interface_type); auto type_name = write_type_name_temp(w, type, "%", true); - //std::cout << type_name << std::endl << std::endl << std::endl; + std::set generic_methods; std::vector nongeneric_delegates; From 1cb8c01bed4a4b32ae1adba22bf1415d6d8529b0 Mon Sep 17 00:00:00 2001 From: UJJWAL CHADHA Date: Thu, 24 Sep 2020 12:08:19 -0400 Subject: [PATCH 21/23] Add tests for IDynamicInterfaceCastable --- UnitTest/TestComponentCSharp_Tests.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/UnitTest/TestComponentCSharp_Tests.cs b/UnitTest/TestComponentCSharp_Tests.cs index 0221f6275..44c9e7448 100644 --- a/UnitTest/TestComponentCSharp_Tests.cs +++ b/UnitTest/TestComponentCSharp_Tests.cs @@ -30,8 +30,23 @@ public class TestCSharp public TestCSharp() { TestObject = new Class(); + } + +#if NET5_0 + [Fact] + public void TestDynamicInterfaceCastingOnValidInterface() + { + var agileObject = (IAgileObject)(IWinRTObject)TestObject; + Assert.NotNull(agileObject); } + [Fact] + public void TestDynamicInterfaceCastingOnInvalidInterface() + { + Assert.ThrowsAny(() => (IStringableInterop)(IWinRTObject)TestObject); + } +#endif + [Fact] public void TestUri() { From 94294d2cfc9325d816d3a8bac03d84ce7b7ecef3 Mon Sep 17 00:00:00 2001 From: UJJWAL CHADHA Date: Fri, 25 Sep 2020 15:45:17 -0400 Subject: [PATCH 22/23] Fix build errors --- .../INotifyCollectionChanged.net5.cs | 6 +- .../Projections/INotifyDataErrorInfo.cs | 2 +- .../INotifyPropertyChanged.net5.cs | 4 +- cswinrt/code_writers.h | 86 ++++++++++++++++--- 4 files changed, 79 insertions(+), 19 deletions(-) diff --git a/WinRT.Runtime/Projections/INotifyCollectionChanged.net5.cs b/WinRT.Runtime/Projections/INotifyCollectionChanged.net5.cs index ad1e24424..b5402f381 100644 --- a/WinRT.Runtime/Projections/INotifyCollectionChanged.net5.cs +++ b/WinRT.Runtime/Projections/INotifyCollectionChanged.net5.cs @@ -23,8 +23,6 @@ public struct Vftbl private delegate* unmanaged _remove_CollectionChanged_1; public delegate* unmanaged[Stdcall] remove_CollectionChanged_1 { get => (delegate* unmanaged[Stdcall])_remove_CollectionChanged_1; set => _remove_CollectionChanged_1 = (delegate* unmanaged)value; } - - private static readonly Vftbl AbiToProjectionVftable; public static readonly IntPtr AbiToProjectionVftablePtr; @@ -46,14 +44,14 @@ static unsafe Vftbl() private static global::System.Runtime.CompilerServices.ConditionalWeakTable> _CollectionChanged_TokenTables = new global::System.Runtime.CompilerServices.ConditionalWeakTable>(); [UnmanagedCallersOnly] - private static unsafe int Do_Abi_add_CollectionChanged_0(IntPtr thisPtr, IntPtr handler, out global::WinRT.EventRegistrationToken token) + private static unsafe int Do_Abi_add_CollectionChanged_0(IntPtr thisPtr, IntPtr handler, global::WinRT.EventRegistrationToken* token) { token = default; try { var __this = global::WinRT.ComWrappersSupport.FindObject(thisPtr); var __handler = global::ABI.System.Collections.Specialized.NotifyCollectionChangedEventHandler.FromAbi(handler); - token = _CollectionChanged_TokenTables.GetOrCreateValue(__this).AddEventHandler(__handler); + *token = _CollectionChanged_TokenTables.GetOrCreateValue(__this).AddEventHandler(__handler); __this.CollectionChanged += __handler; return 0; } diff --git a/WinRT.Runtime/Projections/INotifyDataErrorInfo.cs b/WinRT.Runtime/Projections/INotifyDataErrorInfo.cs index aa9e6ec52..ccaf1e4d3 100644 --- a/WinRT.Runtime/Projections/INotifyDataErrorInfo.cs +++ b/WinRT.Runtime/Projections/INotifyDataErrorInfo.cs @@ -173,7 +173,7 @@ internal INotifyDataErrorInfo(ObjectReference obj) { __propertyName = MarshalString.CreateMarshaler(propertyName); global::WinRT.ExceptionHelpers.ThrowExceptionForHR(_obj.Vftbl.GetErrors_3(ThisPtr, MarshalString.GetAbi(__propertyName), &__retval)); - return global::ABI.System.Collections.Generic.IEnumerable.FromAbi(__retval); + return (global::ABI.System.Collections.Generic.IEnumerable)(object)IInspectable.FromAbi(__retval); } finally { diff --git a/WinRT.Runtime/Projections/INotifyPropertyChanged.net5.cs b/WinRT.Runtime/Projections/INotifyPropertyChanged.net5.cs index 3472bc7b6..8da29bd62 100644 --- a/WinRT.Runtime/Projections/INotifyPropertyChanged.net5.cs +++ b/WinRT.Runtime/Projections/INotifyPropertyChanged.net5.cs @@ -43,14 +43,14 @@ static unsafe Vftbl() private static global::System.Runtime.CompilerServices.ConditionalWeakTable> _PropertyChanged_TokenTables = new global::System.Runtime.CompilerServices.ConditionalWeakTable>(); [UnmanagedCallersOnly] - private static unsafe int Do_Abi_add_PropertyChanged_0(IntPtr thisPtr, IntPtr handler, out global::WinRT.EventRegistrationToken token) + private static unsafe int Do_Abi_add_PropertyChanged_0(IntPtr thisPtr, IntPtr handler, global::WinRT.EventRegistrationToken* token) { token = default; try { var __this = global::WinRT.ComWrappersSupport.FindObject(thisPtr); var __handler = global::ABI.System.ComponentModel.PropertyChangedEventHandler.FromAbi(handler); - token = _PropertyChanged_TokenTables.GetOrCreateValue(__this).AddEventHandler(__handler); + *token = _PropertyChanged_TokenTables.GetOrCreateValue(__this).AddEventHandler(__handler); __this.PropertyChanged += __handler; return 0; } diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index a7728f4de..8d7e18cac 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -871,7 +871,7 @@ set => %.% = value; } else { - return w.write_temp("((%)(IWinRTObject)this)", bind(iface, false, false)); + return w.write_temp("((%)(IWinRTObject)this)", bind(iface, typedef_name_type::Projected, false)); } } @@ -1911,7 +1911,7 @@ db_path.stem().string()); { w.write(R"( private EventSource<%> _%;)", -bind(get_type_semantics(evt.EventType()), false, false), +bind(get_type_semantics(evt.EventType()), typedef_name_type::Projected, false), evt.Name()); } } @@ -2738,7 +2738,7 @@ global::System.Collections.Concurrent.ConcurrentDictionary)((IWinRTObject)this).GetObjectReferenceForType(typeof(%).TypeHandle));\n", - bind(type, false, false)); + bind(type, typedef_name_type::Projected, false)); w.write("var ThisPtr = _obj.ThisPtr;\n"); } }; @@ -2762,7 +2762,7 @@ global::System.Collections.Concurrent.ConcurrentDictionary(type, false, false)); + w.write("%.", bind(type, typedef_name_type::Projected, false)); } }), method.Name(), @@ -2784,7 +2784,7 @@ global::System.Collections.Concurrent.ConcurrentDictionary(type, false, false)); + w.write("%.", bind(type, typedef_name_type::Projected, false)); } }), prop.Name()); @@ -2825,7 +2825,7 @@ global::System.Collections.Concurrent.ConcurrentDictionary { var _obj = (ObjectReference)key.GetObjectReferenceForType(typeof(%).TypeHandle); return %; })", evt.Name(), bind(type, false, false), bind(evt)); + : w.write_temp("_%.GetValue((IWinRTObject)this, (key) => { var _obj = (ObjectReference)key.GetObjectReferenceForType(typeof(%).TypeHandle); return %; })", evt.Name(), bind(type, typedef_name_type::Projected, false), bind(evt)); w.write(R"( %event % %% { @@ -4498,7 +4498,9 @@ public static class % bool write_abi_interface(writer& w, TypeDef const& type) { XLANG_ASSERT(get_category(type) == category::interface_type); - auto type_name = write_type_name_temp(w, type, "%", true); + auto type_name = write_type_name_temp(w, type, "%", typedef_name_type::ABI); + + auto nongenerics_class = w.write_temp("%_Delegates", bind(type, typedef_name_type::ABI, false)); std::set generic_methods; std::vector nongeneric_delegates; @@ -4520,7 +4522,7 @@ internal unsafe interface % : % w.write(distance(type.GenericParam()) > 0 ? "public static Guid PIID = Vftbl.PIID;\n\n" : ""); }, // Vftbl - bind(type, type_name, generic_methods, "", nongeneric_delegates), + bind(type, type_name, generic_methods, nongenerics_class, nongeneric_delegates), bind(type, generic_methods), bind(type), [&](writer& w) { @@ -4531,7 +4533,16 @@ internal unsafe interface % : % } ); - XLANG_ASSERT(nongeneric_delegates.empty()); + if (!nongeneric_delegates.empty()) + { + w.write(R"([global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] +public static class % +{ +%} +)", +nongenerics_class, +bind_each(nongeneric_delegates)); + } w.write("\n"); return true; @@ -4604,6 +4615,57 @@ return global::System.Runtime.InteropServices.CustomQueryInterfaceResult.NotHand settings.netstandard_compat ? "GetReferenceForQI()" : "((IWinRTObject)this).NativeObject"); } + void write_wrapper_class(writer& w, TypeDef const& type) + { + auto type_name = write_type_name_temp(w, type, "%", typedef_name_type::CCW); + auto wrapped_type_name = write_type_name_temp(w, type, "%", typedef_name_type::Projected); + auto default_interface_abi_name = get_default_interface_name(w, type, true); + auto base_semantics = get_type_semantics(type.Extends()); + + w.write(R"(%[global::WinRT.ProjectedRuntimeClass(typeof(%))] +%public %class %% +{ +public %(% comp) +{ +_comp = comp; +} +public static implicit operator %(% comp) +{ +return comp._comp; +} +public static implicit operator %(% comp) +{ +return new %(comp); +} +public static % FromAbi(IntPtr thisPtr) +{ +if (thisPtr == IntPtr.Zero) return null; +var obj = MarshalInspectable.FromAbi(thisPtr); +return obj as %; +} +% +private readonly % _comp; +} +)", +bind(type), +default_interface_abi_name, +bind(type), +bind(type), +type_name, +bind(type, base_semantics, false, true), +type_name, +wrapped_type_name, +wrapped_type_name, +type_name, +type_name, +wrapped_type_name, +type_name, +wrapped_type_name, +type_name, +bind(type, true), +wrapped_type_name); + } + void write_class_netstandard(writer& w, TypeDef const& type) { if (settings.component) @@ -4733,7 +4795,7 @@ _lazyInterfaces = new Dictionary() }), default_interface_name, default_interface_name, - bind(type), + bind(type, false), bind(type)); } @@ -4799,7 +4861,7 @@ private % AsInternal(InterfaceTag<%> _) => _default; bind(type), bind(type), type_name, - bind(type, base_semantics, true), + bind(type, base_semantics, true, false), type_name, default_interface_name, default_interface_name, @@ -4855,7 +4917,7 @@ global::System.Collections.Concurrent.ConcurrentDictionary(type), + bind(type, false), bind(type)); } From b06d2d3089a2156ea14460bda8d442a2fd050151 Mon Sep 17 00:00:00 2001 From: Manodasan Wignarajah Date: Fri, 25 Sep 2020 18:39:05 -0700 Subject: [PATCH 23/23] Fix authoring --- cswinrt/code_writers.h | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/cswinrt/code_writers.h b/cswinrt/code_writers.h index 8d7e18cac..d3355a803 100644 --- a/cswinrt/code_writers.h +++ b/cswinrt/code_writers.h @@ -2738,7 +2738,7 @@ global::System.Collections.Concurrent.ConcurrentDictionary)((IWinRTObject)this).GetObjectReferenceForType(typeof(%).TypeHandle));\n", - bind(type, typedef_name_type::Projected, false)); + bind(type, typedef_name_type::CCW, false)); w.write("var ThisPtr = _obj.ThisPtr;\n"); } }; @@ -2762,7 +2762,7 @@ global::System.Collections.Concurrent.ConcurrentDictionary(type, typedef_name_type::Projected, false)); + w.write("%.", bind(type, typedef_name_type::CCW, false)); } }), method.Name(), @@ -2784,7 +2784,7 @@ global::System.Collections.Concurrent.ConcurrentDictionary(type, typedef_name_type::Projected, false)); + w.write("%.", bind(type, typedef_name_type::CCW, false)); } }), prop.Name()); @@ -2825,7 +2825,7 @@ global::System.Collections.Concurrent.ConcurrentDictionary { var _obj = (ObjectReference)key.GetObjectReferenceForType(typeof(%).TypeHandle); return %; })", evt.Name(), bind(type, typedef_name_type::Projected, false), bind(evt)); + : w.write_temp("_%.GetValue((IWinRTObject)this, (key) => { var _obj = (ObjectReference)key.GetObjectReferenceForType(typeof(%).TypeHandle); return %; })", evt.Name(), bind(type, typedef_name_type::CCW, false), bind(evt)); w.write(R"( %event % %% { @@ -2839,7 +2839,7 @@ remove => %.Unsubscribe(value); { if (!settings.netstandard_compat) { - w.write("%.", bind(type, typedef_name_type::Projected, false)); + w.write("%.", bind(type, typedef_name_type::CCW, false)); } }), evt.Name(), @@ -4517,7 +4517,7 @@ internal unsafe interface % : % // Interface abi implementation bind(type), type_name, - bind(type, typedef_name_type::Projected, false), + bind(type, typedef_name_type::CCW, false), [&](writer& w) { w.write(distance(type.GenericParam()) > 0 ? "public static Guid PIID = Vftbl.PIID;\n\n" : ""); }, @@ -4622,8 +4622,8 @@ return global::System.Runtime.InteropServices.CustomQueryInterfaceResult.NotHand auto default_interface_abi_name = get_default_interface_name(w, type, true); auto base_semantics = get_type_semantics(type.Extends()); - w.write(R"(%[global::WinRT.ProjectedRuntimeClass(typeof(%))] -%public %class %% + w.write(R"( +%%internal %class %% { public %(% comp) { @@ -4648,7 +4648,6 @@ private readonly % _comp; } )", bind(type), -default_interface_abi_name, bind(type), bind(type), type_name, @@ -4801,6 +4800,12 @@ _lazyInterfaces = new Dictionary() void write_class(writer& w, TypeDef const& type) { + if (settings.component) + { + write_wrapper_class(w, type); + return; + } + if (is_static(type)) { write_static_class(w, type);