CLR 学习笔记(一)Hosting
午夜无眠,随手翻到CLR hosting的章节,于是记下一些心得。。
首先是CLR被MS实现成一个COM(MSCorWks.dll中),GUIDs还有接口ICLRRuntimeHost定义在MSCorEE.h中,在于是好奇在SDK中找到打开看看,乖乖,上万行,汗!
对应的MSCorEE.dll在System32下,它其实不实现CLR,只是个跑龙套的(shim),即便一台机器中装有多个版本的CLR,也只有这一个龙套兄(64bit系统上好像对2.0版有些例外),这哥们能找到所有安装版本的CLR.
如果想在一个Windows进程中host CLR,只要调用方法CorBindToRuntimeEx,会返回一个指针ICLRRuntimeHost,这个接口指针可以完成下面这些事情:
- 设置Host managers--告诉CLR,LZ要插手内存分配,线程调度,组建加载,回收垃圾你也得跟俺打声招呼,老NB了;
- 获取CLR managers--还有人事权,那个类/成员能不能用,能不能调,都能管;
- 初始化和启动CLR;
- 在CLR中加载组建并运行代码;
- ....
翠花,上代码:
代码
1 #include <Windows.h>
2 #include <MSCorEE.h>
3 #include <stdio.h>
4
5 void main(int argc, WCHAR **argv) {
6 // Load the CLR
7 ICLRRuntimeHost *pClrHost;
8 HRESULT hr = CorBindToRuntimeEx(
9 NULL, // desired CLR version (NULL=latest)
10 NULL, // desired GC flavor (NULL=workstation)
11 0, // desired startup flags
12 CLSID_CLRRuntimeHost, // CLSID of CLR
13 IID_ICLRRuntimeHost, // IID of ICLRRuntimeHost
14 (PVOID*) &pClrHost); // returned COM interface
15
16 // (This is where you would set Host managers)
17 // (This is where you could get CLR managers)
18
19 // Initialize and start the CLR
20 pClrHost->Start();
21
22 // Load an assembly and call a static method that
23 // takes a String and returns an Int32
24 DWORD retVal;
25 hr = pClrHost->ExecuteInDefaultAppDomain(
26 L"SomeMgdAssem.dll",
27 L"Wintellect.SomeType", L"SomeMethod", L"Jeff", &retVal);
28
29 // Show the result returned from managed code
30 wprintf(L"Managed code returned %d", retVal);
31
32 // Terminate this process (destroying the CLR loaded in it)
33 }
2 #include <MSCorEE.h>
3 #include <stdio.h>
4
5 void main(int argc, WCHAR **argv) {
6 // Load the CLR
7 ICLRRuntimeHost *pClrHost;
8 HRESULT hr = CorBindToRuntimeEx(
9 NULL, // desired CLR version (NULL=latest)
10 NULL, // desired GC flavor (NULL=workstation)
11 0, // desired startup flags
12 CLSID_CLRRuntimeHost, // CLSID of CLR
13 IID_ICLRRuntimeHost, // IID of ICLRRuntimeHost
14 (PVOID*) &pClrHost); // returned COM interface
15
16 // (This is where you would set Host managers)
17 // (This is where you could get CLR managers)
18
19 // Initialize and start the CLR
20 pClrHost->Start();
21
22 // Load an assembly and call a static method that
23 // takes a String and returns an Int32
24 DWORD retVal;
25 hr = pClrHost->ExecuteInDefaultAppDomain(
26 L"SomeMgdAssem.dll",
27 L"Wintellect.SomeType", L"SomeMethod", L"Jeff", &retVal);
28
29 // Show the result returned from managed code
30 wprintf(L"Managed code returned %d", retVal);
31
32 // Terminate this process (destroying the CLR loaded in it)
33 }
确实很强大,下回有机会实战一把