COM 对象 C# 将 MMDeviceEnumerator 转换为 IMMDeviceEnumerator InvalidCastException

COM Objects C# Casting MMDeviceEnumerator to IMMDeviceEnumerator InvalidCastException(COM 对象 C# 将 MMDeviceEnumerator 转换为 IMMDeviceEnumerator InvalidCastException)

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

问题描述

我没有使用 COM 导入的经验,我只是在使用其他人的代码,但对我不起作用

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:COM 对象 C# 将 MMDeviceEnumerator 转换为 IMMDeviceEnumerator InvalidCastException

基础教程推荐