![](/img/trans.png)
[英]How to register for 32-Bit COM interop using Visual Studio 2022
[英]How to check if '32-bit prefered' is toggled using visual studio variables
我制作了一个包含托管和非托管代码的 NuGet 包。 托管代码使用 C# 编写并支持AnyCPU
而非托管代码使用 C++ 编写并具有 32 位和 64 位版本。 此包中的托管代码依赖于非托管代码。 我的包的结构如下所示:
\build
\x86
unmanaged.dll
\x64
unmanaged.dll
package.targets
\lib
\net472
managed.dll
在我的“.targets”文件中,我正在检查$(Platform)
变量以查看用户是否选择了x86
、 x64
或AnyCPU
并将正确的非托管 dll 复制到输出目录:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Condition=" '$(Platform)' == 'x64' ">
<Content Include="$(MSBuildThisFileDirectory)x64\unmanaged.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Link>unmanaged.dll</Link>
</Content>
</ItemGroup>
<ItemGroup Condition=" '$(Platform)' == 'x86' OR '$(Platform)' == 'AnyCPU' ">
<Content Include="$(MSBuildThisFileDirectory)x86\unmanaged.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Link>unmanaged.dll</Link>
</Content>
</ItemGroup>
</Project>
预期的行为是当用户构建他们的程序时,托管 dll 被复制到输出目录,并根据所选的体系结构类型使用正确的 umanaged dll。
当用户选择x86
或x64
,一切都按预期工作,但在选择AnyCPU
时则AnyCPU
。 这是因为如果用户关闭了“32 位首选”并且将 32 位非托管 dll 复制到输出目录,则会引发异常,说明 32 位非托管 dll 的格式与进程不匹配”架构,这是显而易见的。 我想修改我的“.targets”文件,以便它可以识别“32 位首选”是打开还是关闭,并在构建程序时将正确的非托管 dll 复制到输出目录。 是否有预定义的 Visual Studio 变量来检查是否切换了“32 位首选”? 如果没有,是否有另一种方法可以检查“.targets”文件中的“32 位首选”选项?
经过一些个人实验,我找到了解决问题的方法。 我卸载了我的项目以查看是否有任何与“32 位首选”相关的行,我发现一行说<Prefer32Bit>false</Prefer32Bit>
,这意味着我可以将其添加到我的“.targets”文件中:
<ItemGroup Condition=" '$(Platform)' == 'AnyCPU' AND '$(Prefer32Bit)' == 'false' ">
<Content Include="$(MSBuildThisFileDirectory)x64\unmanaged.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Link>unmanaged.dll</Link>
</Content>
</ItemGroup>
<ItemGroup Condition=" '$(Platform)' == 'AnyCPU' AND '$(Prefer32Bit)' == 'true' ">
<Content Include="$(MSBuildThisFileDirectory)x86\unmanaged.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Link>unmanaged.dll</Link>
</Content>
</ItemGroup>
我用我的程序对此进行了测试,看看它是否可行并且成功了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.