EonaCat.VolumeMixer/EonaCat.VolumeMixer/Helpers/ComHelper.cs

53 lines
1.3 KiB
C#

using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace EonaCat.VolumeMixer.Helpers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
internal static class ComHelper
{
public static T GetInterface<T>(IntPtr ptr) where T : class
{
if (ptr == IntPtr.Zero)
{
return null;
}
try
{
return Marshal.GetObjectForIUnknown(ptr) as T;
}
catch
{
return null;
}
finally
{
if (ptr != IntPtr.Zero)
{
Marshal.Release(ptr);
}
}
}
public static async Task ReleaseComObject(object obj)
{
if (obj != null && Marshal.IsComObject(obj))
{
if (obj == null || !Marshal.IsComObject(obj))
{
return;
}
Marshal.ReleaseComObject(obj);
obj = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}