Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COM Objects C# Casting MMDeviceEnumerator to IMMDeviceEnumerator InvalidCastException

Tags:

c#

com

I have no experience with COM Imports and am just working with someone else's code that wasn't working for me

The line of code that is throwing the InvalidCastException:

    IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());

COM Imports:

[Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
internal class MMDeviceEnumerator
{
}

[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IMMDeviceEnumerator
{
    [PreserveSig]
    int EnumAudioEndpoints(EDataFlow dataFlow, DEVICE_STATE dwStateMask, out IMMDeviceCollection ppDevices);

    [PreserveSig]
    int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMMDevice ppEndpoint);

    [PreserveSig]
    int GetDevice([MarshalAs(UnmanagedType.LPWStr)] string pwstrId, out IMMDevice ppDevice);

    [PreserveSig]
    int RegisterEndpointNotificationCallback(IMMNotificationClient pClient);

    [PreserveSig]
    int UnregisterEndpointNotificationCallback(IMMNotificationClient pClient);
}

Screenshot:

enter image description here

like image 954
coderguy22296 Avatar asked Sep 27 '22 02:09

coderguy22296


1 Answers

That's not very close, you are creating a .NET class. Letting the CLR know that this is actually a COM declaration and implemented elsewhere requires using the [ComImport] directive. I'll give you the minimum required declarations:

[ComImport]
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMMDeviceEnumerator
{
    // etc..
}

public static class MMDeviceEnumeratorFactory {
    private static readonly Guid MMDeviceEnumerator = new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E");

    public static IMMDeviceEnumerator CreateInstance() {
        var type = Type.GetTypeFromCLSID(MMDeviceEnumerator);
        return (IMMDeviceEnumerator)Activator.CreateInstance(type);
    }
}

And use it like this:

IMMDeviceEnumerator deviceEnumerator = MMDeviceEnumeratorFactory.CreateInstance();

Do strongly avoid using [PreserveSig], you want a loud bang when a method fails. Do note that this interface is already wrapped by the NAudio library.

like image 88
Hans Passant Avatar answered Oct 13 '22 00:10

Hans Passant