- .NET Core 2.0 By Example
- Rishabh Verma Neha Shrivastava
- 270字
- 2021-06-24 18:31:02
Platform Invoke (P/Invoke)
P/Invoke allows us to access structures and functions of unmanaged libraries from our managed code ASP.NET Core 2.0. To use P/Invoke API, we use the System.Runtime.InteropServices namespace. This namespace allows us to access attributes the way we want, to use them with native components. The DllImport attribute is used for the declaration.
static extern bool AllowSetForegroundWindow(int dwProcessId);
The following diagram demonstrates where Interop stands between native and managed code:
For example, if we want to use the AnyPopup() method of user32.dll, we use it as follows:
using System.Runtime.InteropServices;
public class Demo
{
// Import user32.dll (contains the method we need) and define
// the method corresponding to the native method
[DllImport("user32.dll")]
static extern bool AnyPopup();
public static void Main(string[] args)
{
// Invoke the method as a regular managed method.
AnyPopup();
}
}
In this program, we used the DllImport attribute which calls the dynamic-link library (DLL), and we can use all these methods inside this DLL which is decorated with the _declspec(dllexport) keyword or extern "c". We will discuss more about the import and export of methods from the library in the following section.