Smart Cards in .NET, Part 2 - The Basics
(Page 2 of 6 )
DLLs in the native world contain just the code and no metadata, except for the related exports in one of the tables in the PE Image. But how would the .NET runtime be able to get all the information about the function in a DLL, or the data or inputs .NET expects us to pass to it? Moreover, .NET will need to know whether data is to be returned from the called native function and what kind of data it is. Anyone programming in .NET would be aware of the differences in types in the Managed and Unmanaged world.
The Platform Invoke or the P/Invoke uses the metadata that we provide in our managed code to locate exported functions and marshal their arguments at run time. The following illustration shows this process.

Figure 1 The process of P/Invoke
When one invokes an unmanaged function from managed code the following sequence of actions occurs:
First the Common Language Runtime
- locates the DLL containing the function,
- loads the DLL into memory,
- locates the address of the function in memory and pushes its arguments onto the stack, marshaling data as required, using the standard marshaller or as we specify (it’s worth noting that locating and loading the DLL, and locating the address of the function in memory occur only on the first call to the function)
- transfers control to the unmanaged function.
Also P/Invoke throws exceptions generated by the unmanaged function to the managed caller. In order to locate a function, one must specify at least the name of the function and name of the DLL that contains it. Each exported function will have a start address in the DLL and is called as the Entrypoint. (Note: It’s not that DLLMain!) To invoke a function you should tell the runtime the DLL name and the function name (or the ordinal number).To do so you use the DllImport attribute with the function prototype. To use this attribute you need to include the following statements to your code. This enables us to use the DllImport attribute available to us for use in our code.
[Visual Basic]
Imports System.Runtime.InteropServices
[C#]
using System.Runtime.InteropServices
Now comes the syntax that we may use for declaring such an unmanaged imported function as below. Consider the MesssageBox function that the user32.dll exports for our use. To introduce the MessageBox function in the User32.dll we declare a function (in C#) as
[DllImport("user32.dll")]
public static extern int MessageBox(int hWnd, String text, String caption, uint type);
Next: Two Versions >>
More C# Articles
More By Digvijay Chauhan
|
| · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | | |
|