Skip to content

Suggestion ComWrappers.TryGetComInstance() to improve UX #106979

Closed

Description

@AaronRobinsonMSFT

Background and motivation

It would be nice to have some wrappers that would return other interfaces pointers, something like:

ComWrappers.TryGetComInstance<T>(unwrapped, out nint iface);

that would do the QI so I could call it like this:

ComWrappers.TryGetComInstance<IFoo>(unwrapped, out nint ifoo);

As a "frequent COM flyer", It's quite perturbing to have to juggle between ComWrappers and Marshal classes, actually it would be nice with all that new code to be able to avoid using Marshal completely :-)

Originally posted by @smourier in #106978 (comment)

public abstract partial class ComWrappers
{
+    public bool TryGetComInstance<TInterface>(object instance, CreateComInterfaceFlags flags, out IntPtr result);
}

This could also be an auto-generated method that would be provided on a derived ComWrappers instance. Looking up the IID on TInterface would need to be AOT friendly, which means typeof(TInterface).GUID is out.

API Proposal

The below API is modified from the OP proposal to align with existing API shape and motivating example below.

public abstract class ComWrappers
{
      public IntPtr GetOrCreateComInterfaceForObject(object instance, CreateComInterfaceFlags flags);
+     public IntPtr GetOrCreateComInterfaceForObject(object instance, CreateComInterfaceFlags flags, in Guid interfaceId);
}
public class StrategyBasedComWrappers
{
+     public IntPtr GetOrCreateComInterfaceForObject<TInterface>(object instance, CreateComInterfaceFlags flags);
}
  • Failing to QI for TInterface will trigger an InvalidCastException.
  • Failing to QI for TInterface will still insert into the map.

API Usage

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;

[assembly: DisableRuntimeMarshalling]

namespace ConsoleAotAuthor
{
    internal partial class Program
    {
        static void Main()
        {
            var cw = new StrategyBasedComWrappers();
            var foo = new Foo();

            // Will throw if foo doesn't QI for IFoo.
            nint ifoo = cw.GetOrCreateComInterfaceForObject<Foo, IFoo>(foo, CreateComInterfaceFlags.None);
            GivePointerToComInterface(ifoo);
        }

        [LibraryImport("Dll1.dll")]
        private static partial void GivePointerToComInterface(nint comObject);
    }

    [GeneratedComInterface, Guid("217104c3-ce28-4d13-a32e-ef65ee75edf1")]
    public partial interface IFoo
    {
        void Method(int i);
    }

    [GeneratedComClass]
    public partial class Foo : IFoo
    {
        public void Method(int i) => Console.WriteLine(".NET i:" + i);
    }
}

Alternative Designs

No response

Risks

No response

Activity

  1. added
    untriaged
    on Aug 26, 2024
  2. removed
    untriaged
    on Aug 26, 2024
  3. added
    api-suggestion
    on Aug 26, 2024
  4. dotnet-policy-service commented on Aug 26, 2024

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/interop-contrib
    See info in area-owners.md if you want to be subscribed.

  5. jkoritzinsky commented on Aug 26, 2024

    @jkoritzinsky
    Member

    We could do this as a method on StrategyBasedComWrappers without too much trouble as we have a mechanism to look up interface details.

    On ComWrappers, we'd have to require the user to pass in the IID as there's no Type->IID mechanism at that level.

  6. AaronRobinsonMSFT commented on Aug 26, 2024

    @AaronRobinsonMSFT
    MemberAuthor

    On ComWrappers, we'd have to require the user to pass in the IID as there's no Type->IID mechanism at that level.

    I like that. We could follow what @smourier is alluding to and simply apply the Marshal.QueryInterface signature to the above. That way we have the low level API that we can build upon in derived ComWrappers?

  7. jkoritzinsky commented on Aug 26, 2024

    @jkoritzinsky
    Member

    Yep! I think that's a great way to do it.

  8. jkoritzinsky commented on Aug 26, 2024

    @jkoritzinsky
    Member

    I've updated the top of the issue to be in the API Proposal format and added one more convenience overload that I think would be quite useful.

  9. 13 remaining items

  10. bartonjs commented on Aug 25, 2026

    @bartonjs
    Member

    Video

    • Multiple reviewers thought that the method was caching the value AFTER the QI call. So we recommend taking a look offline and see if a different name/layer would make things clearer. (If not, we're probably happy with the current name)
    • Consider removing the T parameter from the StrategyBasedComWrappers version as it seems like T : TInterface is implied by context.
    namespace System.Runtime.InteropServices;
    
    public partial class ComWrappers
    {
        public IntPtr GetOrCreateComInterfaceForObject(object instance, CreateComInterfaceFlags flags, in Guid interfaceId);
    }
    
    public partial class StrategyBasedComWrappers
    {
        public IntPtr GetOrCreateComInterfaceForObject<T, TInterface>(T instance, CreateComInterfaceFlags flags);
    }
  11. added
    api-needs-work
    and removed
    api-ready-for-review
    on Aug 25, 2026
  12. AaronRobinsonMSFT commented on Aug 25, 2026

    @AaronRobinsonMSFT
    MemberAuthor

    Multiple reviewers thought that the method was caching the value AFTER the QI call. So we recommend taking a look offline and see if a different name/layer would make things clearer. (If not, we're probably happy with the current name)

    This was discussed offline with the interop team. We're going to keep with this approach. We considered additional APIs on ComWrappers but none seemed to improve the ergonomics and largely became just calling Marshal.QueryInterface() and Marshal.Release() in a macro style. Since the use case here was framed as simply asking for an affordance to bundle the known target interface as the return, the proposal is to keep as-is.

    Consider removing the T parameter from the StrategyBasedComWrappers version as it seems like T : TInterface is implied by context.

    Done.

  13. added
    api-ready-for-review
    and removed
    api-needs-work
    on Aug 25, 2026
  14. bartonjs commented on Sep 8, 2026

    @bartonjs
    Member

    Video

    Looks good as proposed.

    namespace System.Runtime.InteropServices;
    
    public partial class ComWrappers
    {
        public IntPtr GetOrCreateComInterfaceForObject(object instance, CreateComInterfaceFlags flags, in Guid interfaceId);
    }
    
    public partial class StrategyBasedComWrappers
    {
        public IntPtr GetOrCreateComInterfaceForObject<TInterface>(object instance, CreateComInterfaceFlags flags);
    }
  15. added
    api-approved
    and removed
    api-ready-for-review
    on Sep 8, 2026
  16. added a commit that references this issue on Sep 26, 2026
    e18128a
  17. locked and limited conversation to collaborators on Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

api-approvedarea-System.Runtime.InteropServices

Type

No type

Projects

  • Status
    No status

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions