1

I am developing a Python library in C++ using pybind11. This library is meant to be used with deep learning packages like TensorFlow, so some of the functions it exposes take TensorFlow objects as argument, and in particular tf.Tensor instances. At C++ level, these functions are defined with the following prototype:

void f(const py11::object& theTensor) {
   ...
}

I'm looking for a way to get the C++ tensorflow::Tensor wrapped by the py11::object that is being passed.

My understanding of TensorFlow is that it uses SWIG to create the Python wrapper to the C++ interface. However, I couldn't find where the tf.Tensor wrapper is defined, and I'm not familiar with the way SWIG exposes C++ classes as Python classes.

I should be able to retrieve a PyObject* pointer from the py11::object using theTensor.ptr(), but then I don't know how to convert this into a pointer to a C++ Tensor object.

sunmat
  • 6,976
  • 3
  • 28
  • 44
  • See the first answer to [this](https://stackoverflow.com/questions/21637732/how-to-pass-list-of-structs-to-c-in-swig-python]). You can do things like `reinterpret_cast(SWIG_Python_GetSwigThis(theTensor))`, but as with any use of `reinterpret_cast` you should definitely verify the pointer you're casting is what you think it is – ChrisD May 09 '19 at 05:07
  • Actually some more digging made me find that the Tensor python class is defined in framework/ops.py so it's not a C++ class exposed "as is" to Python by SWIG. – sunmat May 09 '19 at 14:20

0 Answers0