Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Project static As<> casting methods for access to factories for interops, etc #385

Merged
merged 5 commits into from
Aug 29, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Projections/Test/Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>

<PropertyGroup>
<GenerateTestProjection>true</GenerateTestProjection>
<GenerateTestProjection Condition="'$(GenerateTestProjection)$(Configuration)' == 'Release'">true</GenerateTestProjection>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NoWarn>8305;0618</NoWarn>
</PropertyGroup>
Expand Down
6 changes: 5 additions & 1 deletion TestComponentCSharp/Class.h
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,11 @@ namespace winrt::TestComponentCSharp::implementation

namespace winrt::TestComponentCSharp::factory_implementation
{
struct Class : ClassT<Class, implementation::Class>
struct Class : ClassT<Class, implementation::Class, Windows::Foundation::IStringable>
{
hstring ToString()
{
return L"Class";
}
};
}
6 changes: 5 additions & 1 deletion TestComponentCSharp/ComImports.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ namespace winrt::TestComponentCSharp::implementation
}
namespace winrt::TestComponentCSharp::factory_implementation
{
struct ComImports : ComImportsT<ComImports, implementation::ComImports>
struct ComImports : ComImportsT<ComImports, implementation::ComImports, Windows::Foundation::IStringable>
{
hstring ToString()
{
return L"ComImports";
}
};
}
6 changes: 5 additions & 1 deletion TestComponentCSharp/NonAgileClass.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ namespace winrt::TestComponentCSharp::implementation
}
namespace winrt::TestComponentCSharp::factory_implementation
{
struct NonAgileClass : NonAgileClassT<NonAgileClass, implementation::NonAgileClass>
struct NonAgileClass : NonAgileClassT<NonAgileClass, implementation::NonAgileClass, Windows::Foundation::IStringable>
{
hstring ToString()
{
return L"NonAgileClass";
}
};
}
44 changes: 44 additions & 0 deletions UnitTest/TestComponentCSharp_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,50 @@ public void TestGenericCast()
Assert.Equal(abiView.ThisPtr, abiView.As<WinRT.IInspectable>().As<ABI.System.Collections.Generic.IReadOnlyList<int>.Vftbl>().ThisPtr);
}

[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("96369F54-8EB6-48F0-ABCE-C1B211E627C3")]
internal unsafe interface IStringableInterop
{
// Note: ComInterfaceType.InterfaceIsIInspectable no longer supported
void GetIids(out int iidCount, out IntPtr iids);
void GetRuntimeClassName(out IntPtr className);
void GetTrustLevel(out TrustLevel trustLevel);

void ToString(out IntPtr hstr);
}

[ComImport]
[Guid("39E050C3-4E74-441A-8DC0-B81104DF949C")]
[InterfaceType(ComInterfaceType.InterfaceIsIInspectable)]
manodasanW marked this conversation as resolved.
Show resolved Hide resolved
public interface IUserConsentVerifierInterop
{
IAsyncOperation<Windows.Security.Credentials.UI.UserConsentVerificationResult> RequestVerificationForWindowAsync(
IntPtr appWindow,
out IntPtr message,
ref Guid riid);
}

[Fact]
public unsafe void TestFactoryCast()
{
IntPtr hstr;

// Access nonstatic class factory
var instanceFactory = Class.As<IStringableInterop>();
instanceFactory.ToString(out hstr);
Assert.Equal("Class", MarshalString.FromAbi(hstr));

// Access static class factory
var staticFactory = ComImports.As<IStringableInterop>();
staticFactory.ToString(out hstr);
Assert.Equal("ComImports", MarshalString.FromAbi(hstr));

// Test user class
var interop = Windows.Security.Credentials.UI.UserConsentVerifier.As<IUserConsentVerifierInterop>();
Assert.NotNull(interop);
}

[Fact]
public void TestFundamentalGeneric()
{
Expand Down
28 changes: 1 addition & 27 deletions WinRT.Runtime/CastExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,33 +42,7 @@ public static TInterface As<TInterface>(this object value)

using (var objRef = GetRefForObject(value))
{
if (typeof(TInterface).GetCustomAttribute(typeof(System.Runtime.InteropServices.ComImportAttribute)) is object)
{
unsafe
{
static WinRT.Interop.IUnknownVftbl MarshalIUnknown(IntPtr thisPtr)
{
var vftblPtr = Unsafe.AsRef<WinRT.VftblPtr>(thisPtr.ToPointer());
var vftblIUnknown = Marshal.PtrToStructure<WinRT.Interop.IUnknownVftbl>(vftblPtr.Vftbl);
return vftblIUnknown;
}

Guid iid = typeof(TInterface).GUID;
IntPtr comPtr;
MarshalIUnknown(objRef.ThisPtr).QueryInterface(objRef.ThisPtr, ref iid, out comPtr);
try
{
var obj = Marshal.GetObjectForIUnknown(comPtr);
return (TInterface)obj;
}
finally
{
MarshalIUnknown(comPtr).Release(comPtr);
}
}
}

return (TInterface)typeof(TInterface).GetHelperType().GetConstructor(new[] { typeof(IObjectReference) }).Invoke(new object[] { objRef });
return objRef.AsInterface<TInterface>();
}
}

Expand Down
21 changes: 21 additions & 0 deletions WinRT.Runtime/ObjectReference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,27 @@ public unsafe ObjectReference<T> As<T>(Guid iid)
return ObjectReference<T>.Attach(ref thatPtr);
}

public unsafe TInterface AsInterface<TInterface>()
{
if (typeof(TInterface).GetCustomAttribute(typeof(System.Runtime.InteropServices.ComImportAttribute)) is object)
{
Guid iid = typeof(TInterface).GUID;
Marshal.ThrowExceptionForHR(VftblIUnknown.QueryInterface(ThisPtr, ref iid, out IntPtr comPtr));
try
{
return (TInterface)Marshal.GetObjectForIUnknown(comPtr);
}
finally
{
var vftblPtr = Unsafe.AsRef<WinRT.VftblPtr>(comPtr.ToPointer());
var vftblIUnknown = Marshal.PtrToStructure<WinRT.Interop.IUnknownVftbl>(vftblPtr.Vftbl);
vftblIUnknown.Release(comPtr);
}
}

return (TInterface)typeof(TInterface).GetHelperType().GetConstructor(new[] { typeof(IObjectReference) }).Invoke(new object[] { this });
}

public int TryAs<T>(out ObjectReference<T> objRef) => TryAs<T>(GuidGenerator.GetIID(typeof(T)), out objRef);

public virtual unsafe int TryAs<T>(Guid iid, out ObjectReference<T> objRef)
Expand Down
56 changes: 44 additions & 12 deletions cswinrt/code_writers.h
Original file line number Diff line number Diff line change
Expand Up @@ -1033,19 +1033,10 @@ remove => %.% -= value;

std::string write_static_cache_object(writer& w, std::string_view cache_type_name, TypeDef const& class_type)
{
auto cache_interface =
w.write_temp(
R"((new BaseActivationFactory("%", "%.%"))._As<ABI.%.%.Vftbl>)",
class_type.TypeNamespace(),
class_type.TypeNamespace(),
class_type.TypeName(),
class_type.TypeNamespace(),
cache_type_name);

w.write(R"(
internal class _% : ABI.%.%
{
public _%() : base(%()) { }
public _%() : base(%._factory._As<ABI.%.%.Vftbl>()) { }
private static WeakLazy<_%> _instance = new WeakLazy<_%>();
internal static % Instance => _instance.Value;
}
Expand All @@ -1054,7 +1045,9 @@ internal static % Instance => _instance.Value;
class_type.TypeNamespace(),
cache_type_name,
cache_type_name,
cache_interface,
class_type.TypeName(),
class_type.TypeNamespace(),
cache_type_name,
cache_type_name,
cache_type_name,
cache_type_name);
Expand Down Expand Up @@ -1205,6 +1198,7 @@ MarshalInspectable.DisposeAbi(ptr);

void write_attributed_types(writer& w, TypeDef const& type)
{
bool factory_written{};
for (auto&& [interface_name, factory] : get_attributed_types(w, type))
{
if (factory.activatable)
Expand All @@ -1217,6 +1211,44 @@ MarshalInspectable.DisposeAbi(ptr);
}
else if (factory.statics)
{
if (!factory_written)
{
factory_written = true;

bool has_base_factory{};
auto extends = type.Extends();
while(!has_base_factory)
{
auto base_semantics = get_type_semantics(extends);
if (std::holds_alternative<object_type>(base_semantics))
{
break;
}
for_typedef(w, base_semantics, [&](auto base_type)
{
for (auto&& [_, base_factory] : get_attributed_types(w, base_type))
{
if (base_factory.statics)
{
has_base_factory = true;
break;
}
}
extends = base_type.Extends();
});
}

w.write(R"(
internal static %BaseActivationFactory _factory = new BaseActivationFactory("%", "%.%");
public static %I As<I>() => _factory.AsInterface<I>();
)",
has_base_factory ? "new " : "",
type.TypeNamespace(),
type.TypeNamespace(),
type.TypeName(),
has_base_factory ? "new " : "");
}

write_static_members(w, factory.type, type);
}
}
Expand Down Expand Up @@ -4255,6 +4287,7 @@ private % AsInternal(InterfaceTag<%> _) => _default;
bind([&](writer& w)
{
bool has_base_type = !std::holds_alternative<object_type>(get_type_semantics(type.Extends()));

if (!type.Flags().Sealed())
{
w.write(R"(
Expand All @@ -4272,7 +4305,6 @@ default_interface_abi_name,
bind<write_lazy_interface_initialization>(type));
}


std::string_view access_spec = "protected ";
std::string_view override_spec = has_base_type ? "override " : "virtual ";

Expand Down
5 changes: 5 additions & 0 deletions cswinrt/strings/WinRT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,10 @@ internal class BaseActivationFactory
{
private ObjectReference<IActivationFactoryVftbl> _IActivationFactory;

public ObjectReference<IActivationFactoryVftbl> Value { get => _IActivationFactory; }

public I AsInterface<I>() => _IActivationFactory.AsInterface<I>();

public BaseActivationFactory(string typeNamespace, string typeFullName)
{
var runtimeClassId = typeFullName.Replace("WinRT", "Windows");
Expand Down Expand Up @@ -289,6 +293,7 @@ internal class ActivationFactory<T> : BaseActivationFactory
public ActivationFactory() : base(typeof(T).Namespace, typeof(T).FullName) { }

static WeakLazy<ActivationFactory<T>> _factory = new WeakLazy<ActivationFactory<T>>();
public new static I AsInterface<I>() => _factory.Value.Value.AsInterface<I>();
public static ObjectReference<I> As<I>() => _factory.Value._As<I>();
public static ObjectReference<I> ActivateInstance<I>() => _factory.Value._ActivateInstance<I>();
}
Expand Down