Class in cpp accessing torch classes and methods


I’m interested in combining python code with cpp code.
I read about custom cpp extension, extending torchscript, and c++ frontend.

I would like to create a class written in cpp and use it from python code. The cpp class must be able to access tensor objects and methods (as done in, while still being used as done in (
The first link I added shows how to create methods in c++ that access torch classes and methods and the code is compiled using script, the second link shows how to use a class in c++ that does not use torch classes and methods (the example is a stack class) and is it compiled using cmake.

Is it possible to sort of combine the two? I want to create a class in cpp and be able to access torch classes and methods, then load the class and use it from python code.


You should absolutely be able to use e.g. torch::Tensor instead of std::string for the method. Note that the “modern” way of extending PyTorch is CustomOperators rather than “vanilla” C++ extensions.

Best regards


Thank you for your answer, but that is not exactly what I’m asking.
What I’m asking is:
In this example -, we see an example of LLTM class. In this example “forward” and “backward” methods are implemented in cpp and called from python “forward” and “backward” methods, instead of the python implementation.
Is it possible to write the whole LLTM class in cpp and use it from python, instead of just the methods?