环境:
pytorch 1.3.1 release cpu版,windows 10 ,visual studio 2017 community版
D盘新建example-app目录
在example-app目录 新建CMakeLists.txt:
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(example-app)
find_package(Torch REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")
if(NOT Torch_FOUND)
message(FATAL_ERROR "Pytorch Not Found!")
endif(NOT Torch_FOUND)
message(STATUS "Pytorch status:")
message(STATUS " libraries: ${TORCH_LIBRARIES}")
add_executable(example-app example-app.cpp)
target_link_libraries(example-app "${TORCH_LIBRARIES}")
set_property(TARGET example-app PROPERTY CXX_STANDARD 14)
# 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)
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放入C++源文件:example-app.cpp
使用windows的命令行工具,切换到example-app目录
执行以下命令(编译的是release版本):
mkdir build
cd build
cmake -DCMAKE_PREFIX_PATH="D:/libtorch" -DCMAKE_BUILD_TYPE=Release -G "Visual Studio 15 Win64" ..
cmake --build . --config Release
其中"D:/libtorch" 是pytorch的C++版解压后的路径。
命令结束后,用visual studio打开 build目录下生成的文件 example-app.vcxproj。
选择x64、release模式运行。
此时会报一个错误:
程序无法启动ALL_BUILD 拒绝访问
将工程中的ALL_BUILD、 ZERO_CHECK项目卸载即可解决。