COM Objects C# Casting MMDeviceEnumerator to 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
基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01