In the current project often need to call the system API, or third-party APIs, and these APIs are usually not based on. NET, which is called the unmanaged function, fortunately. NET provides us with platform invoke service, through this service, we can easily achieve our needs.
Call process is actually relatively simple, mainly divided into the following several steps:
1) Find the definition of the function and the link library (DLL file) where he is located
As an example of a system-provided beep function (beeps with a specified frequency and time), he is defined in the dynamic link library Kernel32.dll.
On MSDN You can find his function signed as BOOL Beep (DWORD dwfreq,dword dwduration), you can see that the function should accept two unsigned integers as arguments, the first is the frequency, the second is the duration, and a BOOL value is returned.
2) Create a function prototype in managed code
Knowing the location and signature of the function, you can write a managed definition for him. Look at the code below.
C#-code:
Using System.Runtime.InteropServices; [DllImport ("bool Beep (uint dwduration);
The namespace System.Runtime.InteropServices is referenced first, and he contains all the required classes for the platform invocation, and then uses the DllImport The Kernel32.dll property tells the compiler that the function is defined in the link library, because the link library is in the System32 directory, so we do not need to specify an absolute path. Note that you must use the static and extern modifiers to declare that the function is an external implementation, and that the signature of the function should be consistent with the original. Of course, we can also modify the name of the function, you must specify an entry point, such as:
C#-code:
[DllImport ("kernel32.dll", EntryPoint = "bool Beep2 (uint dwduration);
EntryPoint indicates the name of the original function.
3) Call
Since then we can invoke the function as if it were managed code, and here's the complete code
C#-code:
Using System.Runtime.InteropServices;
Namespace ConsoleApplication1 {Class Program {Staticvoid Main (string[] args) { for (uint i = 100; I <= 20000; i++) { Beep (i, 5); } }
[DllImport ("kernel32.dll")] static extern bool Beep (uint Dwfreq, uint dwduration); }
Note: You can also put the Beep function in a separate class, but declare it as a public type
Of course, this is just one of the simplest examples, when it comes to data type conversions and function callbacks, it's a lot more complicated, so let's just take it as an opening.
Report:
to view the definition of the system API, refer to the MSDN Win32 and COM development
to find out more about the API invocation methods, please refer to the P/invoke
For more instructions on the DllImport property, refer to MSDN
How C # calls an unmanaged function (GO)