如何在.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"
},
project.json
中的
dependencies属性指定包依赖项,因此 NuGet 将
NameOfDll.dll
作为包 ID 处理,而不是作为 dll 名称。
要将本机 C++ dll 添加到
.xproj
库的 NuGet 包中,您应该执行以下步骤:
NameOfDll.dll
放在\lib
目录下MyClassLibrary.xproj
打开
project.json
文件并在其中添加:
"packOptions": {
"files" : {
"includeFiles" : "lib/NameOfDll.dll"
}
}
执行
dotnet pack
NameOfDll.dll
将包含在路径lib\NameOfDll.dll
. 下的 NuGet 包中
要将本机 C++ dll 添加到
.csproj
库的 NuGet 包中,您应该执行以下步骤:
MyClassLibrary.csproj
的项目。nuget spec
命令为您的类库创建新的 NuGet 包。\lib
附近创建\build
、\content
、\tools
和MyClassLibrary.nuspec
目录。\build
文件夹中。.native
.在
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>
提示:
.targets
内容摘自this问题。
上面的 .targets
文件将在安装 NuGet 包时被注入到目标项目文件中。将以下行添加到您的
MyClassLibrary.nuspec
中:
<files>
<file src="lib\" target="lib" />
<file src="tools\" target="tools" />
<file src="content\" target="content" />
<file src="build\" target="build" />
</files>
执行
nuget pack MyClassLibrary.csproj
构建您的 NuGet 包。这是在 .net core 2 中的一键式方法。我在我的网站上使用它并且有效。
在解决方案资源管理器中右键单击您的项目,选择添加->现有项,浏览并选择您的 dll(选择显示所有扩展)。然后你的 dll 将出现在解决方案资源管理器中。
在解决方案资源管理器中,右键单击您的 dll -> 属性。设置构建操作:内容,并复制到输出目录:如果更新则复制(或始终复制)。
完成了。像这样在代码中直接使用你的 dll:
[DllImport("my_dll.dll", CallingConvention = CallingConvention.Cdecl)]