libtorch win10上使用
下载
wget https://download.pytorch.org/libtorch/cpu/libtorch-shared-with-deps-2.2.1%2Bcpu.zip
说明
libtorch使用MSVC编译,需要本机安装,并在IDE中使用MSVC工具链。
下载官方libtorch包,或者本机安装了python环境,并且安装了pytorch。(pytorch核心是c++编写的,pytorch包含了libtorch的所有内容)
编译最好使用与libtorch相同的版本,debug/release,避免各种链接问题。下面的配置中是读取的torch_home环境变量进行获取的libtorch包目录,可以手动配置。
如果是python环境安装的pytorch,可以在python中使用以下方式获取torch_home:
import torch
print(torch.utils.cmake_prefix_path)
配置CMakeLists.txt:
set(torch_home $ENV{torch_home})
find_package(Torch 2.2.1 REQUIRED HINTS ${torch_home})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")
add_executable(example-app example-app.cpp)
#add_library(example-app SHARED example-app.cpp)
target_link_libraries(example-app "${TORCH_LIBRARIES}")
set_property(TARGET example-app PROPERTY CXX_STANDARD 17)
# The following code block is suggested to be used on Windows.
# According to https://github.com/pytorch/pytorch/issues/25457,
# the DLLs need to be copied to avoid memory errors.
if (MSVC)
message("MSVC, torch home:" ${TORCH_INSTALL_PREFIX})
file(GLOB TORCH_DLLS "${TORCH_INSTALL_PREFIX}/lib/*.dll")
add_custom_command(TARGET example-app
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${TORCH_DLLS}
$<TARGET_FILE_DIR:example-app>) # 放入目标所在的目录
endif (MSVC)
example-app.cpp
#include <torch/torch.h>
#include <iostream>
int main() {
torch::Tensor tensor = torch::rand({2, 3});
std::cout << tensor << std::endl;
}
---
本文来自博客园,作者:Bingmous,转载请注明原文链接:https://www.cnblogs.com/bingmous/p/18503396