0

I am trying to build an executable using C++ and design a function having multi-dim tensor array value.

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

int main() {
    torch::Tensor tensor = torch::rand({1, 400, 400});
    /* print out or return 'tensor' value somehow*/
    return 0
}

And I would like to get the tensor value from Python side using the executable file.

Although there are some posts about retrieving stdout of executable in Python using subprocess (such as this example), I don't see approaches on how to get the numerically equal variable value of cpp function in Python using executable.

Even if I try to std::cout tensor value in cpp, the printed value is cutoff as below. So, it is not numerically equal with the original value in cpp.

  ...
  2.5478e-01  2.9543e-01  9.1405e-01  7.1981e-01
  6.6557e-01  1.6238e-01  3.8278e-01  4.9424e-01
  5.1383e-01  1.6593e-01  8.5924e-01  3.8744e-01
  9.9829e-01  4.2506e-02  1.2164e-01  8.0078e-03
  4.3933e-02  9.7834e-01  9.4632e-01  5.5783e-01
  6.2664e-01  6.1711e-02  1.9250e-01  9.3781e-01
  8.9360e-01  8.6810e-01  2.5314e-01  8.9651e-01
  1.2310e-01  6.8445e-02  8.3720e-01  5.6933e-01
[ CPUFloatType{1,400,400} ]

Can I get any advices on this issue? Thank you very much.

4
  • main can only return int, you need to print out your result instead Commented Jul 7, 2022 at 4:31
  • You can return any value from an executable, this is the return value from main. Then from python you can get that code as described here : csatlas.com/python-subprocess-run-exit-code Commented Jul 7, 2022 at 5:11
  • You'll need to modify the cpp program's printing routine to print the exact values rather than rounded-off approximations -- you could do that by calling the appropriate iostream methods, or if you don't like the C++ iostream API, you could replace the cout-based printing routine with one that uses printf() or similar instead. Once you have it printing out values that you can use, then it's just a matter of updating your Python program to parse those values. Commented Jul 7, 2022 at 5:45
  • You could also consider compiling your functions into a shared library and then loading it in python using ctypes. Another option could be to use PyBind to expose some bindings for your functions written in C/C++. Commented Jul 10, 2022 at 19:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.