How can I solve error when build cpp file including "torch/script.h"?

15 次查看(过去 30 天)
I'm trying to make interface b/w matlab and c++ library defined in py2cpp.cpp file declared by py2cpp.hpp which is header file. And py2cpp.cpp file includes torch/script.h; hence, when build at matlab, error occurs as, "fatal error: torch/script.h: No such file or directory #include <torch/script.h> "
I downloaded Libtorch and checked that the code runs well in visual studio(VS) code 2022 by adding directory of Libtorch in VS project path. I think error occurs because matlab can find Libtorch file unlike VS, but I don't know how to add directory of Libtorch to PATH in matlab.
version info.
matlab: R2021b
compiler in matlab: MinGW64 Compiler (C++)
Test codes are following:
1) py2cpp.cpp
#include <torch/script.h>
#include <py2cpp.h>
#include <iostream>
#include <memory>
namespace py2cpp{
void model(){
std::cout << "Hello MATLAB!\n";
}
}
2) py2cpp.hpp
#pragma once
namespace py2cpp{
void model();
}
3) matlab command
sdf
mex -setup cpp
productPath = fullfile(matlabroot,'extern','examples','cpp_interface');
hppFile = 'py2cpp_model4_1.hpp';
cppFile = 'py2cpp_model4_1.cpp';
clibgen.generateLibraryDefinition(fullfile(productPath,hppFile), ...
"SupportingSourceFiles",fullfile(productPath,cppFile), ...
"OverwriteExistingDefinitionFiles",true, ...
"ReturnCArrays",false) % treat output as MATLAB arrays
build(definepy2cpp)
py2cpp.cpp and py2cpp.hpp codes are in productPath(defined in MATLAB code)
I'm new to C++ and Libtorch, so there can be a lot of ill-coded statement. Plz advice to me more specifically.

采纳的回答

Rishav
Rishav 2023-9-4
编辑:Rishav 2023-9-5
Hi YoungSeo,
I understand that you are facing an error as, "fatal error: torch/script.h: No such file or directory #include <torch/script.h> ".
Open MATLAB and the change your current working directory to the location where your C++ files (py2cpp.cpp and py2cpp.hpp) are located. Use the following command for the same:
cd /path_to_your_cpp_files
Set the include path to LibTorch using the following command:
mex -I/path_to_libtorch_include py2cpp.cpp
Here, replace the "/path_to_libtorch_include" with the actual path of the 'include' directory of your LibTorch installation.
Then compile and run your code. This will allow MATLAB to find the "torch/script.h" header file during the compilation process.

更多回答(0 个)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by