COM对象C#将MMDeviceEnumerator转换为IMMDeviceEnumerator InvalidCastException [英] COM Objects C# Casting MMDeviceEnumerator to IMMDeviceEnumerator InvalidCastException

查看:237
本文介绍了COM对象C#将MMDeviceEnumerator转换为IMMDeviceEnumerator InvalidCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有使用COM Imports的经验,只是在使用别人的代码而对我不起作用

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

抛出InvalidCastException的代码行:

The line of code that is throwing the InvalidCastException:

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

COM导入:

[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);
}

屏幕截图:

推荐答案

那不是很紧密,您正在创建.NET类。让CLR知道这实际上是一个COM声明,并且已在其他地方实现,需要使用[ComImport]指令。我将为您提供最少的必需声明:

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);
    }
}

并像这样使用它:

IMMDeviceEnumerator deviceEnumerator = MMDeviceEnumeratorFactory.CreateInstance();

请务必避免使用[PreserveSig],当方法失败时,您要大声敲打。请注意,该接口已经被NAudio库包装。

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.

这篇关于COM对象C#将MMDeviceEnumerator转换为IMMDeviceEnumerator InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆