使用 .nuspec 和 .targets (C++)

问题描述

正在努力将编译的 c++ dll(x86 和 x64)打包以便 C# 库可以使用它。

使用 nuspec 文件设法打包和推送 dll,但是当使用 VS2019 包管理器时,它成功安装了包,但是没有出现参考。 (任何 cpu

.nuspec

<?xml version="1.0"?>
<package >
    <Metadata>
        <id>component1</id>
        <version>1.0.0</version>
        <description>mycomponent</description>
        <authors>Me</authors>
    </Metadata> 
    <files>
        <file src="32\component1.dll"   target="build\x86" />
        <file src="64\component1.dll"   target="build\x64" />
        <file src="component1.targets"   target="lib\net40" />
    </files>
</package>

由于消费项目的目标是 .NET 4.0,我创建了一个指向相同框架的 component1.targets 文件

.目标

<ItemGroup Condition=" '$(Platform)' == 'x64' ">
    <Reference Include="component1">
              <HintPath>"$(MSBuildThisFileDirectory)..\..\build\x64\component1.dll"</HintPath>
    </Reference>
</ItemGroup>

<ItemGroup Condition=" '$(Platform)' == 'x86' OR '$(Platform)' == 'Anycpu' OR '$(Platform)' == 'Any cpu' ">
    <Reference Include="component1">
              <HintPath>$(MSBuildThisFileDirectory)..\..\build\x32\component1.dll</HintPath>
    </Reference>
</ItemGroup>

解决方法

你的步骤一团糟。

您应该注意目标文件应该命名为 .targets`,与 nuget 包 ID 同名,否则将无法工作。见this link

另外,目标文件应该放在nupkgbuild文件夹中。

这是两个重要的提示。

1)请将您的 nuspec 文件更改为:

<?xml version="1.0"?>
<package >
    <metadata>
        <id>component1</id>
        <version>1.0.0</version>
        <description>mycomponent</description>
        <authors>Me</authors>
    </metadata> 
    <files>
        <file src="32\component1.dll"   target="build\x86" />
        <file src="64\component1.dll"   target="build\x64" />
        <file src="component1.targets"   target="build" />
    </files>
</package>

2) 然后,将您的 component1.targets 更改为:

您应该删除 "" 下的 "$(MSBuildThisFileDirectory)..\..\build\x64\component1.dll"

<Project>

<ItemGroup Condition=" '$(Platform)' == 'x64' ">
    <Reference Include="component1">
              <HintPath>$(MSBuildThisFileDirectory)..\build\x64\component1.dll</HintPath>
    </Reference>
</ItemGroup>

<ItemGroup Condition=" '$(Platform)' == 'x86' OR '$(Platform)' == 'AnyCPU' OR '$(Platform)' == 'Any CPU' ">
    <Reference Include="component1">
              <HintPath>$(MSBuildThisFileDirectory)..\build\x32\component1.dll</HintPath>
    </Reference>
</ItemGroup>

</Project>

3) 使用 nuget pack 重新打包 nuget 包。在安装此新版本的 nuget 软件包之前,请clean nuget caches first 或删除 C:\Users\xxx(current user name)\.nuget\packages 下的所有文件。

它在我身边运行良好。

我的 nuget 包名为 testt,我在 ClassLibrary21.dll 下引用了 x64

enter image description here