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.

jdw
  • 21
  • 3
  • `main` can only return `int`, you need to print out your result instead – Alan Birtles Jul 07 '22 at 04: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 : https://csatlas.com/python-subprocess-run-exit-code/ – Pepijn Kramer Jul 07 '22 at 05: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. – Jeremy Friesner Jul 07 '22 at 05:45
  • You could also consider compiling your functions into a shared library and then loading it in python using [ctypes](https://docs.python.org/3/library/ctypes.html). Another option could be to use [PyBind](https://pybind11.readthedocs.io/en/stable/basics.html) to expose some bindings for your functions written in C/C++. – kalgoritmi Jul 10 '22 at 19:14

0 Answers0