bingmous

欢迎交流,不吝赐教~

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

统计

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;
}

posted on   Bingmous  阅读(89)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示