COM Objects C# Casting MMDeviceEnumerator to IMMDeviceEnumerator InvalidCastException

 ̄綄美尐妖づ 提交于 2019-12-06 04:27:58

问题


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

回答1:


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.




回答2:


I guess your MMDeviceEnumerator class should implement the interface.

In other words, change

internal class MMDeviceEnumerator
{
}

To:

internal class MMDeviceEnumerator : IMMDeviceEnumerator
{
}


来源:https://stackoverflow.com/questions/31928429/com-objects-c-sharp-casting-mmdeviceenumerator-to-immdeviceenumerator-invalidcas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!