C++ API with MEX compiler - Interfacing PyTorch and Matlab


for some scientific application I need to interface PyTorch and Matlab (only for inference).
I thought the best way would be not to mix the two interpreted languages (python and matlab) but rather load the trained models via the C++ API and interface this with the MATLAB C++ interface.
Does someone have experience with this already?

Since MATLAB uses MEX “compiler” which is some kind of wrapper around the OS default compiler (clang++ in my case) it’s kind of hard to use cmake for this and I get tons of linking errors and I wondered if someone could help or has already tried something like this.

Cheers :slight_smile:

The best way is to call Python within Matlab, and use data files for communication.

I have managed to interface MEX and PyTorch using CMake. But, I am facing problems when I try to run module.forward(…) function. Matlab basically hangs when I run “forward” function. I may be able to help with CMake if you are still interested in that.

Yeah would be interested! For the moment I

  • Compile a shared library with my pytorch stuff (nicely in CMAKE)
  • have a quick and dirty solution for compiling the mex files via direct compiler command but that’s super ugly.

Do you have an example?
Forwarding works for me. if I can help, let me know.