.NET MAUI项目引用原生C++ DLL问题:DLL未复制到输出目录
.NET MAUI原生互操作DLL未复制到输出目录的解决办法
你的问题出在NativeReference仅负责让编译器识别原生依赖,但不会自动将DLL复制到输出目录,再加上.NET MAUI的输出结构和常规.NET项目有差异,导致文件未被同步过去。以下是几种可行的修复方案:
方案1:为NativeReference添加复制属性
修改.csproj中的配置,给NativeReference加上复制相关属性,确保文件被同步到输出目录:
<ItemGroup Condition="'$(RuntimeIdentifier)' == 'win-x64'"> <NativeReference Include="External\MyInterop.dll"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> </NativeReference> </ItemGroup>
方案2:搭配Content项处理复制
如果方案1无效,可以同时使用Content项来强制复制文件,保留NativeReference让编译器识别依赖:
<ItemGroup Condition="'$(RuntimeIdentifier)' == 'win-x64'"> <NativeReference Include="External\MyInterop.dll" /> <Content Include="External\MyInterop.dll"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> <Link>MyInterop.dll</Link> </Content> </ItemGroup>
方案3:验证RuntimeIdentifier配置
确保VS中当前构建的目标运行时是win-x64(右键项目→属性→生成→目标运行时),否则你的Condition条件会跳过该配置块的执行。
方案4:用PostBuildEvent强制复制
如果以上方案都不生效,添加构建后事件命令手动复制文件:
<Target Name="CopyNativeDll" AfterTargets="Build" Condition="'$(RuntimeIdentifier)' == 'win-x64'"> <Copy SourceFiles="External\MyInterop.dll" DestinationFolder="$(OutputPath)" /> </Target>
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

