官术网_书友最值得收藏!

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.

If you want to dig more into the details, online resources are available at:  http://www.pinvoke.net  . It has all the functions which are widely used.
For example: AllowSetForegroundWindow (user32)—this enables the mentioned process to set the foreground window by utilizing the  SetForegroundWindow method; the only condition is that the calling process should be able to set the foreground window. In C# code, we will write it as: 
[DllImport("user32.dll")]
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.

主站蜘蛛池模板: 临澧县| 平南县| 萨嘎县| 北海市| 吉林市| 福建省| 安化县| 达日县| 赣榆县| 满城县| 榆林市| 新河县| 房产| 罗定市| 胶南市| 宜君县| 太仓市| 个旧市| 靖宇县| 莱阳市| 萨嘎县| 方正县| 石门县| 铁岭市| 曲靖市| 林芝县| 宜阳县| 湖口县| 苍梧县| 杭州市| 安塞县| 米泉市| 上犹县| 响水县| 雅江县| 武邑县| 南投县| 九寨沟县| 拉萨市| 泊头市| 鞍山市|