Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a substitue for System.Runtime.InteropServices.Marshal.GetActiveObject() in .NET Core?

Tags:

.net

com

The method GetActiveObject() is available in System.Runtime.InteropServices.Marshal in .NET Framework, but not in .NET Core (https://stackoverflow.com/a/58010881/180275).

Is there a way around if I want to use .NET Core (from PowerShell 7)?

like image 461
René Nyffenegger Avatar asked Nov 02 '25 00:11

René Nyffenegger


1 Answers

Here is an equivalent implementation that works for .NET core 3.1+ on Windows (and .NET framework):

public static object GetActiveObject(string progId, bool throwOnError = false)
{
    if (progId == null)
        throw new ArgumentNullException(nameof(progId));

    var hr = CLSIDFromProgIDEx(progId, out var clsid);
    if (hr < 0)
    {
        if (throwOnError)
            Marshal.ThrowExceptionForHR(hr);

        return null;
    }

    hr = GetActiveObject(clsid, IntPtr.Zero, out var obj);
    if (hr < 0)
    {
        if (throwOnError)
            Marshal.ThrowExceptionForHR(hr);

        return null;
    }
    return obj;
}

[DllImport("ole32")]
private static extern int CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] string lpszProgID, out Guid lpclsid);

[DllImport("oleaut32")]
private static extern int GetActiveObject([MarshalAs(UnmanagedType.LPStruct)] Guid rclsid, IntPtr pvReserved, [MarshalAs(UnmanagedType.IUnknown)] out object ppunk);

I'm not a Powershell expert, but I think you can port that to Powershell or use a bit of C# directly in Powershell.

like image 66
Simon Mourier Avatar answered Nov 04 '25 17:11

Simon Mourier