引言
在有時候的開發過程中,我們會遇到需要調用系統的API,不巧的是.Net Core可能沒辦法為我們提供相關的調用方式。那需要如何才能解決這個問題呢?
這時候我們就可能會考慮借鑒現成的別人寫好的代碼或者自己編寫相關代碼。
由於.Net Core沒辦法提供相關調用那就可能考慮使用其他的方式來實現目的,比如說使用
DllImport進行擴展。
什么是DllImport
DllImport是System.Runtime.InteropServices命名空間下的一個屬性類,其功能是提供從非托管DLL(托管/非托管是微軟的.net framework中特有的概念,其中,非托管代碼也叫本地(native)代碼。與Java中的機制類似,也是先將源代碼編譯成中間代碼(MSIL,Microsoft Intermediate Language),然后再由.net中的CLR將中間代碼編譯成機器代碼。)導出的函數的必要調用信息。
DllImport屬性應用於方法,要求最少要提供包含入口點的dll的名稱。
.NetCore如何使用(.Net 系基本都可以參考此方法)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
// DllImport所在命名空間
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
namespace HelloWord
{
public class TestController : Controller
{
// dll文件名稱及待調用方法
[DllImport("helloword.dll")]
public static extern string hello();
[HttpGet]
public IActionResult Index()
{
return new ContentResult()
{
Content = hello()
};
}
}
}
擴展
.Net Core是一跨平台的,絕大多數會運行與Windows或者Linux上(OSX未實踐),那如何讓代碼一次書寫能在兩個平台都進行兼容呢?在不考慮DllImport導入的動態庫的兼容性問題的前提下。可以采用不標明后綴的方式進行聲明。
// Windows下的動態鏈接庫為 helloword.dll
// Linux下的動態鏈接庫為 hellowrd.so
// 這樣的寫法只能兼容其中一種
[DllImport("helloword.dll")]
public static extern string hello();
// 通過這種寫法可以兼容這兩種
[DllImport("helloword")]
public static extern string hello();
DllImport尋找順序
- 絕對路徑
- exe所在目錄
- System32目錄
- 環境變量目錄
