概述:如何在代码中使用 mscoree
0x01 添加 mcsoree.cs
// MSCOREE.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace mscoree
{
[CompilerGenerated]
[Guid("CB2F6722-AB3A-11D2-9C40-00C04FA30A3E")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[TypeIdentifier]
[ComImport]
[CLSCompliant(false)]
public interface ICorRuntimeHost
{
void _VtblGap1_11();
void EnumDomains(out IntPtr enumHandle);
void NextDomain([In] IntPtr enumHandle, [MarshalAs(UnmanagedType.IUnknown)] out object appDomain);
void CloseEnum([In] IntPtr enumHandle);
}
}0x02 添加导出函数
private static ICorRuntimeHost GetCorRuntimeHost()
{
return (ICorRuntimeHost)Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("CB2F6723-AB3A-11D2-9C40-00C04FA30A3E")));
}0x03 使用
ICorRuntimeHost host = null;
host = GetCorRuntimeHost();0x04 获取所有 AppDomains
static void GetAllAppDomains()
{
AppDomain one = AppDomain.CreateDomain("One");
AppDomain two = AppDomain.CreateDomain("Two");
// Creates 2 app domains
List<AppDomain> appDomains = new List<AppDomain>();
IntPtr enumHandle = IntPtr.Zero;
ICorRuntimeHost host = null;
host = GetCorRuntimeHost();
try
{
host.EnumDomains(out enumHandle);
object domain = null;
AppDomain tempDomain;
while (true)
{
host.NextDomain(enumHandle, out domain);
if (domain == null)
{
break;
}
tempDomain = domain as AppDomain;
appDomains.Add(tempDomain);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
host.CloseEnum(enumHandle);
int rel = Marshal.ReleaseComObject(host);
}
Assembly[] assemblies;
foreach (AppDomain app in appDomains)
{
Console.WriteLine(app.FriendlyName);
assemblies = app.GetAssemblies();
Console.WriteLine("-----------------------Assemblies------------------");
foreach (Assembly assem in assemblies)
{
Console.WriteLine(assem.FullName);
}
Console.WriteLine("---------------------------------------------------");
}
}
---
## 扩展阅读
> **📖 文章:在 .NET 中运行非托管代码的骚操作**
>
> 来源:[先知社区 - aliyun.com](https://xz.aliyun.com/news/9256)
>
> **说明**:本文讲"原生代码怎么 host CLR",那篇文章讲"托管代码怎么调原生"——两个方向互为镜像。内容包括:
>
> - **Fcall / Qcall**:CLR 内部的快速调用路径,托管→非托管
> - **Marshal.GetDelegateForFunctionPointer**:将函数指针转委托,底层支撑所有 P/Invoke
> - 从 .NET 内部深入调用 native API 的各种技巧
>
> **阅读量**:⭐⭐⭐⭐(进阶 / 4/5)
> - 前提:熟悉 C# / .NET,了解 CLR 基本运行机制
> - 适合:想深入理解 .NET 与原生代码互操作机理的开发者