Skip to content

[API Proposal]: Add ability to safely get the managed object from a ComWrappers CCW #79674

@JeremyKuhne

Description

@JeremyKuhne

Background and motivation

Using COM Interop it is a common pattern to cast incoming RCW's against internal instances. WinForms does this in a number of places. For example, we check incoming OLE control interfaces to see if they are our own hosting control and utilize fields/methods on the instance if it is.

Using ComWrappers this isn't possible to do safely without adding an additional interface to the outgoing CCW. It would be good to add functionality to ComWrappers to query for a wrapped managed object on any IUnknown.

Without a way for users to construct ComWrappers CCWs that we can attempt to unwrap when receiving from native methods they cannot enable trimming in their apps.

API Proposal

namespace System.Runtime.InteropServices;

public abstract class ComWrappers
{
+    public static bool TryGetObject(void* unknown, out object? obj);
}

API Usage

public static MyCallbackApi(IUnknown* unknown)
{
   if (ComWrappers.TryGetObject(unknown, out object? myObject)
       && myObject is MyObject)
   {
        // Do stuff
   }
}

Alternative Designs

We could potentially publish a new COM interface that we can have users implement in their ComWrappers CCWs that we can look for to know that it is ok to unwrap with ComInterfaceDispatch.GetInstance.

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.Runtime.InteropServicesblockingMarks issues that we want to fast track in order to unblock other important work

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions