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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With