.NetCore创建Native Dll(Winx64,Mac.
![](https://img.haomeiwen.com/i3902031/7ad6673a509c4d89.jpg)
本文原创by superowner,转载请注明出处,现在像本宫这样原创的可不多了
首先下载官网最新包https://github.com/dotnet/corert,下载最新的zip包
不要下载他的release版本,好久没更新了
这个项目,主要是依赖于ILCompiler这个编译器,把IL代码编译为本地代码
意思就是可以脱离.Net环境直接运行!和C++创建的Dll没有区别(使用上),
性能也基本接近原生C++的性能
OK,直接操作
首先,安装.Net Core2.x,虽然现在有3.x预览版出来了,但是,然并卵,bug奇多
下载后进入这个目录
![](https://img.haomeiwen.com/i3902031/b1d7222cc692ef86.png)
然后按下Shift键和鼠标右键,以powershell模式运行,表想太多
就是cmd换个皮肤
复制以下到powershell,回车运行
dotnet publish /p:NativeLib=Shared -r win-x64 -c release
网速好的话,大概20s吧就可以生成dll了,网速差就看人品了
目前windows只支持x64,里面的参数Shared就是dll,Static就是lib
PS:生成完dll后必须丢到C#程序的Debug/Release目录下,一般我们64bit系统的电脑默认Any CPU配置下默认走的x64,如果没有第三方强制需要x64配置的就不需要配置
OK,切换到C#控制台程序
首先,我们看看源码函数格式:
![](https://img.haomeiwen.com/i3902031/3c3e8a334dd7b16b.png)
然后把EntryPoint = "add", CallingConvention = CallingConvention.StdCall抄过去
完整C#调用代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace TestCoreRTDllFromNetCore
{
class Program
{
[DllImport("NativeLibrary.dll", EntryPoint = "add", CallingConvention = CallingConvention.StdCall)]
public extern static int Add(int a,int b);
static void Main(string[] args)
{
try
{
Console.WriteLine(Add(2, 3));
}
catch { }
Console.ReadKey();
}
}
}
运行结果:是不是很神奇?
![](https://img.haomeiwen.com/i3902031/fdda284f9e46699c.png)
![](https://img.haomeiwen.com/i3902031/afa73ecda285f75f.png)
dll体积的话...认真你就输了(逃跑)
这个可以把自己的核心代码dll弄起来,但是前提是,代码必须支持.Net Core
以上是创建dll流程,exe的也差不多,详见git的Markdown文档
ref:https://www.cnblogs.com/hongmaju/p/4727173.html
ref:https://github.com/dotnet/corert
ref:https://www.jianshu.com/p/45c1a842a949 简书添加代码模块,备忘