|
Loading Assemblies Using ICLRRuntimeHostIn addition to the managed assembly loading APIs discussed so far, the CLR provides a method that enables you to load an assembly and execute one of its methods using the unmanaged CLR hosting interfaces. This method, named ICLRRuntimeHost::ExecuteInDefaultAppDomain, is useful when you need to use the hosting interfaces to customize some aspect of the CLR, but don't have a need to write any managed code as part of your host. These scenarios aren't very common, but I could imagine needing to write a host that customizes how the CLR loads domain-neutral code using IHostControl or that enforces specific programming model constraints using ICLRHostProtectionManager, for example. In these scenarios, the customizations are available only through the CLR hosting interfaces. If these are the only customizations you need to make, and if your only other requirement is to be able to execute a managed method in the default application domain, ExecuteInDefaultAppDomain can satisfy your needs. ExecuteInDefaultAppDomain loads an assembly given a filename. In addition to supplying the path to the assembly you want to load, you must supply the name of the method you want to execute and the name of the type that method is in. The method you supply must have a specific signatureit must be static, return an int, and have one string argument: static int MethodName(string argument) If you attempt to call a method with a signature other this, ExecuteInDefaultAppDomain returns with an HRESULT of 0x80131513 (COR_E_MISSINGMETHOD). The parameters to ExecuteInDefaultAppDomain are shown in Table 7-2.
Listing 7-1 shows a simple CLR host that uses ExecuteInDefaultAppDomain to execute a method in an assembly. In this example, I call CorBindToRuntimeEx to initialize the CLR and to get a pointer to the ICLRRuntimeHost interface. Given that pointer, I call ExecuteInDefaultAppDomain, passing in the path of the assembly to load along with the name of the method to execute. Listing 7-1. ExecApp.cpp#include "stdafx.h" #include <mscoree.h> int main(int argc, wchar_t* argv[]) { ICLRRuntimeHost *pCLR = NULL; // initialize the CLR HRESULT hr = CorBindToRuntimeEx( L"v2.0.41013", L"wks", NULL, CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (PVOID*) &pCLR); assert(SUCCEEDED(hr)); // Any specific CLR customizations would be done here. // Start the CLR hr = pCLR->Start(); assert(SUCCEEDED(hr)); // Execute the application. DWORD retVal = 0; hr = pCLR->ExecuteInDefaultAppDomain(L"RealEstate.exe", L"RealEstate.Program", L"Start", NULL, &retVal); assert(SUCCEEDED(hr)); return retVal; } |
|