![](/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.