托管 DLL 与非托管 DLL
托管代码是由公共语言运行时 (CLR)提供代码的管理,包括提取、编译、执行、安全等等,非托管代码是由 C/C++ 编译的二进制机器码,默认为 非托管模式,需要由软件开发人员来负责一系列管理操作。
C# 调用托管 DLL
创建一个 .NET 6 控制台应用程序,项目根目录创建一个
Lib
目录,放置 dll 文件打开
.csproj
文件,在Project
节点内添加这段代码:<ItemGroup> <Reference Include=".\Lib\ManagedDll.dll"></Reference> </ItemGroup>
调用 dll
static void Main(string[] args) { //调用ManagedDll.dll中的方法 Console.WriteLine(ManagedDll.SayHi()); }
C# 调用非托管 DLL
创建一个类:
ThirdDll.cs
using System.Runtime.InteropServices; namespace DllSample { public class ThirdDll { [DllImport(@".\Lib\UnManagedDll.dll",EntryPoint = "SayHi")] public static extern void SayHi(); } }
调用 dll
static void Main(string[] args) { //调用UnManagedDll.dll中的方法 Console.WriteLine(SayHi()); }