COM Objects C# Casting MMDeviceEnumerator to IMMDe

2019-04-10 23:59发布

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:

    i.stack.imgur.com/SZODi.png

标签: c# com
2条回答
淡お忘
2楼-- · 2019-04-11 00:53

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-04-11 00:54

I guess your MMDeviceEnumerator class should implement the interface.

In other words, change

internal class MMDeviceEnumerator
{
}

To:

internal class MMDeviceEnumerator : IMMDeviceEnumerator
{
}
查看更多
登录 后发表回答