How to load python tensor in C++?

So I copied the code from https://github.com/pytorch/pytorch/issues/20356#issuecomment-567663701 but I got exception: c10::Error at memory location at torch::pickle_load. Anyone know how to fix it ?
My python code:

    x = torch.arange(10)
    f = io.BytesIO()
    torch.save(x, f, _use_new_zipfile_serialization=True)
    # send f wherever
    with open('test.pt', "wb") as outfile:
        # Copy the BytesIO stream to the output file
        outfile.write(f.getbuffer())

My C++ code:

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

std::vector<char> get_the_bytes(std::string filename) {
    std::ifstream input(filename, std::ios::binary);
    std::vector<char> bytes(
        (std::istreambuf_iterator<char>(input)),
        (std::istreambuf_iterator<char>()));

    input.close();
    return bytes;
}

int main()
{
    std::vector<char> f = get_the_bytes("path\\to\\test.pt");
    torch::IValue x = torch::pickle_load(f);
    torch::Tensor tensor = x.toTensor();
    std::cout << tensor;
}

1 Like

@Kenisy
Check your libtorch version and pytorch version. It might because you have different versions.