Marshal.GetIUnknownForObject(Object) Method

Definition

Returns an IUnknown interface from a managed object.

C#
[System.Security.SecurityCritical]
public static IntPtr GetIUnknownForObject(object o);
C#
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public static IntPtr GetIUnknownForObject(object o);
C#
public static IntPtr GetIUnknownForObject(object o);

Parameters

o
Object

The object whose IUnknown interface is requested.

Returns

IntPtr

The IUnknown pointer for the o parameter.

Attributes

Examples

The following example demonstrates how to retrieve an IUnknown interface for a managed object using the GetIUnknownForObject method.

C#
using System;
using System.Runtime.InteropServices;

class Program
{

    static void Run()
    {

        // Create an int object
        int obj = 1;

        Console.WriteLine("Calling Marshal.GetIUnknownForObject...");

        // Get the IUnKnown pointer for the Integer object
        IntPtr pointer = Marshal.GetIUnknownForObject(obj);

        Console.WriteLine("Calling Marshal.Release...");

        // Always call Marshal.Release to decrement the reference count.
        Marshal.Release(pointer);
    }

    static void Main(string[] args)
    {
        Run();
    }
}

Remarks

In managed code, you seldom work directly with the IUnknown interface. However, GetIUnknownForObject is useful when calling a method that exposes a COM object parameter as an IntPtr type, or with custom marshaling. Calling an object with this method causes the reference count to increment on the interface pointer before the pointer is returned. Always use Marshal.Release to decrement the reference count once you have finished with the pointer. This method provides the opposite functionality of the Marshal.GetObjectForIUnknown method.

You can also use this method on a managed object to obtain an interface pointer to the COM Callable Wrapper for the object.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

See also