Managed code invokes unmanaged code. NET provides the P/invoke (platform invoke) way that it acts as. NET is based on a variety of books and network resources, this is no longer discussed here. So how does unmanaged code invoke managed code? We know that a managed application is first started by the operating system, and then the CLR is invoked by the operating system to host the program. So. NET Framework in what way does the operating system get to know it and can start it? Microsoft actually implemented it as a COM server in a DLL and provided a standard COM interface. Since it is a COM service, it means that ordinary unmanaged programs can also invoke the CLR to run managed code, calling it a boarding, calling an unmanaged program that calls the CLR a host. Not only can the host call the CLR, it can also be used for advanced management such as memory management, garbage collection management, policy management, event management, and line-controlled programming.
1.1 Core Component MSCOREE.DLL
Mscoree. DLL is responsible for selecting. NET versions, invoking and initializing the CLR, and so on. An unmanaged program that wants to start the CLR must also reference MSCOREE.DLL, using its export function to load managed code and perform operations such as customizing the CLR. Now that the focus is on MSCOREE.DLL, let's look at it together.
View header files for MSCOREE.DLL
We have no way to view the source code for the MSCOREE.DLL file, but the Framework SDK provides a mscoree.h file that can be viewed in the relevant version of the SDK installation directory. Because the file is very large, the source code is not posted here for analysis. The related interfaces and functions are then introduced.
Mscoree. DLL's export function
Starting DumpBin.exe at the command line, execute the following code to view the list of exported functions for MSCOREE.DLL:
C:\windows\ystem32>dumpbin/exports Mscoree. Dll
The result is shown in Figure 1-3.
Figure 1-3 Output MSCOREE.DLL List of exported functions
From the results of the run can be known, Mscoree. There are more than 100 exported functions in a DLL, all of which can be called publicly, and an explanation of each function can be found on MSDN. Here are just a few of the common functions.
CorBindToRuntimeEx function
The function is used by the host to load the CLR, which is defined as shown in Listing 1-4.
Code Listing 1-4 CorBindToRuntimeEx function definition
HRESULT CorBindToRuntimeEx (
[In] LPWStr pwszversion,
[In] LPWStr Pwszbuildflavor,
[In] DWORD Startupflags,
[In] Refclsid Rclsid,
[In] REFIID riid,
[out] lpvoid* PPV
);