.Net Core下DllImport使用方法及扩展

引言

​ 在有时候的开发过程中,我们会遇到需要调用系统的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寻找顺序

  1. 绝对路径
  2. exe所在目录
  3. System32目录
  4. 环境变量目录 
posted @ 2021-09-05 11:54  一块白板  阅读(2097)  评论(0编辑  收藏  举报