Files
Svetlana Karslioglu 19da3da3d3 Restructure C++ docs (#174096)
The fix-cpp-build branch is a major restructuring that:

- Drops Exhale (which auto-generated API docs but caused OOM in CI) in favor of hand-written RST pages using Breathe directives
- Reorganizes notes into a hierarchical API reference with proper categories
- Adds new content: XPU docs, stable ABI docs, DeviceGuard/Stream docs
- Always runs Doxygen instead of gating on an env var

Pull Request resolved: https://github.com/pytorch/pytorch/pull/174096
Approved by: https://github.com/janeyx99, https://github.com/seemethere, https://github.com/albanD
2026-04-07 17:24:38 +00:00

1.8 KiB

myst
myst
html_meta
description keywords
Custom classes in PyTorch C++ — registering C++ classes for use in TorchScript and Python. PyTorch, C++, custom class, TorchScript, TORCH_CLASS, registration

Custom Classes

PyTorch allows registering custom C++ classes that can be used from Python and TorchScript.

Header: torch/custom_class.h

class_ Template

:members:
:undoc-members:

Example:

#include <torch/custom_class.h>

struct MyClass : torch::CustomClassHolder {
    int value;

    MyClass(int v) : value(v) {}

    int getValue() const { return value; }
    void setValue(int v) { value = v; }
};

TORCH_LIBRARY(my_classes, m) {
    m.class_<MyClass>("MyClass")
        .def(torch::init<int>())
        .def("getValue", &MyClass::getValue)
        .def("setValue", &MyClass::setValue)
        .def_readwrite("value", &MyClass::value);
}

Registering Methods

Constructor:

m.class_<MyClass>("MyClass")
    .def(torch::init<int>())  // Constructor taking int

Methods:

m.class_<MyClass>("MyClass")
    .def("getValue", &MyClass::getValue)
    .def("setValue", &MyClass::setValue)

Properties:

m.class_<MyClass>("MyClass")
    .def_readwrite("value", &MyClass::value)   // Read-write
    .def_readonly("const_value", &MyClass::const_value)  // Read-only

Using Custom Classes

From C++:

auto my_obj = c10::make_intrusive<MyClass>(42);
int val = my_obj->getValue();

From Python:

import torch
torch.classes.load_library("path/to/library.so")
obj = torch.classes.my_classes.MyClass(42)
print(obj.getValue())

In TorchScript:

@torch.jit.script
def use_my_class(x: torch.classes.my_classes.MyClass) -> int:
    return x.getValue()