如何在 .NET 中创建用于外部引用的 DLL?

How can I create a DLL for external referencing in .NET?

我正在尝试使用简单的 .NET Core Class 库项目创建 DLL。我希望能够通过外部引用 DLL 文件来使用公开的方法。

例如,我的简单 Class 库项目包含一个打印“test”的方法。

public class TestDLL
{
    public static void PrintTest()
    {
        Console.WriteLine("test");
    }
}

我通过使用 DLLImport 属性引用它来调用最终的 DLL。

public class Program
{
    public static void Main(string[] args)
    {
        PrintTest();
    }

    [DllImport(@"C:\dev\TestDLL\bin\x64\Debug\netcoreapp3.1\test.dll")]
    public static extern void PrintTest();
}

编译后,我disassemble DLL文件,手动添加.export描述符到PrintTest方法中,以暴露它。下面显示的是 disassembled IL 文件的片段。

.method public hidebysig static void  PrintTest() cil managed
{
  // Code size       13 (0xd)
  .export [1]          // manually inserted descriptor
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldstr      "test"
  IL_0006:  call       void [System.Console]System.Console::WriteLine(string)
  IL_000b:  nop
  IL_000c:  ret
} // end of method TestDLL::PrintTest

最后,我assemble把文件做成一个DLL并调用它。尽管在插入 .export 描述符后文件被成功引用,但我得到一个异常。

Unhandled exception. System.Runtime.InteropServices.SEHException (0x80004005): 
External component has thrown an exception.
  at ConsoleApp.Program.PrintTest()
  at ConsoleApp.Program.Main(String[] args) in 
  C:\dev\test\ConsoleApp\Program.cs:line 11
                                
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or
assembly
  'System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
  or one of its dependencies. The system cannot find the file specified.

我尝试将 System.Runtime.dll 文件放在与我调用的 DLL 相同的文件夹中,但这也无济于事。我错过了什么?

正如 Hans Passant 所建议的那样,使用 DllExport 就可以了。

此包依赖于将相同的 .export 描述符插入到目标项目的 IL 文件中,以便在创建 DLL 后公开某些方法。但是,此包还负责目标 .csproj 文件的许多其他必要配置属性。因此,在使用 .NET 和 Visual Studio.

时,仅添加 .export 描述符是不够的

同样重要的是要提到,要让它工作,我需要为我的 Class 库项目从使用 .NET Core 切换到 .NET Standard 2.0,因为我无法让它工作(出于盒子)既没有 .NET Core 也没有 .NET 6.0。