Почему `sessionManager.getSessionEnumerator` всегда терпит неудачу с AccessViolationException?C#

Место общения программистов C#
Ответить
Anonymous
 Почему `sessionManager.getSessionEnumerator` всегда терпит неудачу с AccessViolationException?

Сообщение Anonymous »

Я работал над приложением C#, которое взаимодействует с API Windows Audio, чтобы проверить процессы, используемые основным устройством рендеринга. Тем не менее, я продолжаю столкнуться с проблемой, в которой вызов SessionManager.getSessionEnumerator всегда терпит неудачу с помощью AccessViolationException . Вот соответствующая часть моего кода: < /p>
using System;
using System.Runtime.InteropServices;

namespace SystemAudio
{
public static class AudioChecker
{
static void Main()
{
int sessionCount;
sessionCount = CheckPrimaryRenderDeviceProcesses();
Console.WriteLine(sessionCount);
}

public static int CheckPrimaryRenderDeviceProcesses()
{
IMMDeviceEnumerator enumerator = (IMMDeviceEnumerator)new MMDeviceEnumerator();

IMMDevice device;
enumerator.GetDefaultAudioEndpoint(0, 0, out device);

string id;
device.GetId(out id);
Console.WriteLine("Primary Render Device ID: " + id);

// Activate IAudioSessionManager2 on the device (also tested with IAudioSessionManager)
Guid IID_IAudioSessionManager2 = new Guid("77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F");
int CLSCTX_ALL = 23;
device.Activate(ref IID_IAudioSessionManager2, CLSCTX_ALL, IntPtr.Zero, out object oSessionManager);

IAudioSessionManager2 sessionManager = (IAudioSessionManager2)oSessionManager;

// Attempt to get the session enumerator.
// This is ALWAYS failing with these error:
// System.AccessViolationException:
// 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
sessionManager.GetSessionEnumerator(out IAudioSessionEnumerator sessionEnumerator);

sessionEnumerator.GetCount(out int sessionCount);
return sessionCount;
}
}
}
< /code>
А вот определения интерфейса COM, которые я использую. Для неиспользованных методов я только что перечислял методы, как определено в VTable, но без каких-либо параметров: < /p>
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
public class MMDeviceEnumerator { }

[ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMMDeviceEnumerator
{
int EnumAudioEndpoints();
int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
int GetDevice();
int RegisterEndpointNotificationCallback();
int UnregisterEndpointNotificationCallback();
}

[ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMMDevice
{
int Activate(ref Guid iid, int dwClsCtx, IntPtr pActivationParams,
[MarshalAs(UnmanagedType.IUnknown)] out object ppInterface);
int OpenPropertyStore();
int GetId([MarshalAs(UnmanagedType.LPWStr)] out string ppstrId);
int GetState();
}

[ComImport, Guid("BFA971F1-4D5E-40BB-935E-967039BFBEE4"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAudioSessionManager
{
int GetAudioSessionControl();
int GetSimpleAudioVolume();
}

[ComImport, Guid("77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAudioSessionManager2 : IAudioSessionManager
{
int GetSessionEnumerator(out IAudioSessionEnumerator sessionEnum);
int RegisterSessionNotification();
int UnregisterSessionNotification();
int RegisterDuckNotification();
int UnregisterDuckNotification();
}

[ComImport, Guid("E2F5BB11-0570-40CA-ACDD-3AA01277DEE8"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAudioSessionEnumerator
{
int GetCount(out int count);
int GetSession();
}

[ComImport, Guid("F4B1A599-7266-4319-A8CA-E70ACB11E8CD"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAudioSessionControl
{
int GetState();
int GetDisplayName();
int SetDisplayName();
int GetIconPath();
int SetIconPath();
int GetGroupingParam();
int SetGroupingParam();
int RegisterAudioSessionNotification();
int UnregisterAudioSessionNotification();
}

[ComImport, Guid("bfb7ff88-7239-4fc9-8fa2-07c950be9c6d"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAudioSessionControl2 : IAudioSessionControl
{
new int GetState();
new int GetDisplayName();
new int SetDisplayName();
new int GetIconPath();
new int SetIconPath();
new int GetGroupingParam();
new int SetGroupingParam();
new int RegisterAudioSessionNotification();
new int UnregisterAudioSessionNotification();
int GetSessionIdentifier();
int GetSessionInstanceIdentifier();
int GetProcessId();
int IsSystemSoundsSession();
int SetDuckingPreferences();
}

Несмотря на следование документации и сведения о реализации, вызов GetseSessionEnumerator сбое невозможно сбое за исключением:
System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
< /code>
Я не уверен, что вызывает эту проблему, и это был довольно блокировщик для моего проекта. Любые понимание или предложения о том, что может пойти не так или с тем, как устранение их дальнейшего количества, будут высоко оценены! Заранее спасибо за вашу помощь. < /P>


Подробнее здесь: https://stackoverflow.com/questions/794 ... cessviolat
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»