如何在.NET Core项目中添加C++库

gem*_*423 13 c++ dll .net-core

如何在.NET Core项目(类库)中添加C++库的方法.我尝试创建一个nuget包但不起作用.我收到了这个错误:

An unhandled exception of type 'System.DllNotFoundException' occurred in "NameOfDll.dll"

当我添加nuget包时,project.json添加以下引用:

  "dependencies": {
    "Core": "1.0.0-*",
    "NETStandard.Library": "1.6.0",
    "NameOfDll.dll": "1.0.0"
  },
Run Code Online (Sandbox Code Playgroud)

Nik*_*ita 12

dependencies属性project.json指定包依赖关系,因为此NuGet处理NameOfDll.dll为包ID,但不是dll名称.

要将库中的原生C++ dll添加到NuGet包中,.xproj您应该执行以下步骤:

  1. 把你NameOfDll.dll\lib目录放在附近MyClassLibrary.xproj
  2. 打开project.json文件并添加:

    "packOptions": {
      "files" : {
        "includeFiles" : "lib/NameOfDll.dll"
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 执行 dotnet pack

NameOfDll.dll将被包含在路径下的NuGet包中lib\NameOfDll.dll.

要将本机C++ dll添加到.csproj库的NuGet包中,您应该执行以下步骤:

  1. 我假设您有名称的托管项目MyClassLibrary.csproj.
  2. 使用nuget spec命令为您的类库创建新的NuGet包.
  3. 创建\lib,\build,\content\tools附近的目录MyClassLibrary.nuspec.
  4. 将所有本机dll复制到该\build文件夹中.
  5. 将复制的本机dll的扩展名更改为.native.
  6. MyClassLibrary.targets\build文件夹内创建以下内容:

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <ItemGroup>
        <AvailableItemName Include="NativeBinary" />
      </ItemGroup>
      <ItemGroup>
        <NativeBinary Include="$(MSBuildThisFileDirectory)*">
          <TargetPath></TargetPath>
        </NativeBinary>
      </ItemGroup>
      <PropertyGroup>
        <PrepareForRunDependsOn>
          $(PrepareForRunDependsOn);
          CopyNativeBinaries
        </PrepareForRunDependsOn>
      </PropertyGroup>
      <Target Name="CopyNativeBinaries" DependsOnTargets="CopyFilesToOutputDirectory">
        <Copy SourceFiles="@(NativeBinary)"
              DestinationFiles="@(NativeBinary->'$(OutDir)\%(TargetPath)\%(Filename).dll')"
              Condition="'%(Extension)'=='.native'">
          <Output TaskParameter="DestinationFiles" ItemName="FileWrites" />
        </Copy>
        <Copy SourceFiles="@(NativeBinary)"
              DestinationFiles="@(NativeBinary->'$(OutDir)\%(TargetPath)\%(Filename).%(Extension)')"
              Condition="'%(Extension)'!='.native'">
          <Output TaskParameter="DestinationFiles" ItemName="FileWrites" />
        </Copy>
      </Target>
    </Project>
    
    Run Code Online (Sandbox Code Playgroud)

    提示:.targets内容取自问题.上述.targets文件将在NuGet包的安装中注入到目标项目文件中.

  7. 将以下行添加到您的MyClassLibrary.nuspec:

    <files>
      <file src="lib\" target="lib" />
      <file src="tools\" target="tools" />
      <file src="content\" target="content" />
      <file src="build\" target="build" />
    </files>
    
    Run Code Online (Sandbox Code Playgroud)
  8. 执行nuget pack MyClassLibrary.csproj以构建NuGet包.

  • 谢谢你的帮助@Nikita (2认同)