Can libtorch return torch::Tensor to pytorch with pybind11?

I need do something on libtorch, then return Tensor to pytorch, implement by pybind11

code snip:

#include <torch/torch.h>
#include <pybind11/pybind11.h>
#include <iostream>

torch::Tensor create()
    return torch::rand({2, 3});

PYBIND11_MODULE(example, m)
    m.doc() = "libtorch tensor test";
    m.def("create", &create, "create tensor");

when I execute “example.create()” in Python, error occur:

TypeError: Unable to convert function return value to a Python type! The signature was
() → at::Tensor

How can I do that correctly? Hope for your help!

I guess it is because “torch::Tensor” is not bound in pybind11, but how to bind it? And make the bound “torch::Tensor” and “pytorch tensor” the same type?

Yes, PyTorch can do it, but you need to import the right header, I think

#include <torch/extension.h>

will do the trick.

The background is that the Python bits are the thing you would not want to include when you are using libtorch purely in C++, so you want more than just torch/torch.h if you use Python.

Best regards


Thanks for your reply, are you saying that as long as the torch/extension.h file is included? is there any example for reference?

when I only include torch/extension.h, error occur while import in python

ImportError: /home/work/test_libtorch/build/ undefined symbol: _Z16THPVariable_WrapN2at6TensorE

1 Like

@tom Oh I see the tutorial, it’s helpful!

From my experience you need to import torch before loading the extension module unless you link to the extension

I also get ImportError undefined symbol: _Z16THPVariable_WrapN2at10TensorBaseE
I added #include <torch/extension.h> in my cpp file, but still it doens’t work