Matlab Mex C++
Back then when I was I starting to learn CUDA, I used to verify some of the functionality by writing to text files and then reading it back to Matlab. As you can guess, this is not an extra efficient way to verify your algo and so it wasn’t long before I moved on to investigation of how to directly interfere with your custom CUDA C/C++ stuff directly from Matlab. Eventhough it may sound difficult, it is in fact quite easy and the requirements are in fact pretty much the same for CUDA. I do highly recommend to start from an empty C/C++ project within Visual Studio IDE and do the modifications below:
- Properties → General → Configuration Type → Change to: Dynamic Library “.dll“
- Properties → Advanced → TargetFileExtrension → Change to: “.mexw64“
- Properties → Linker → Command Line→ Additional Options → Add: “/export:mexFunction“
- Properties → Linker → Input → AdditionalDependencies → Add: “libmat.lib libmex.lib libmx.lib“
- Properties → VC++ Directories → Include Directories → Add: “C:\Program Files\MATLAB\R2022b\extern\include“
- Properties → VC++ Directories → Library Directories → Add: “C:\Program Files\MATLAB\R2022b\extern\lib\win64\microsoft“
The code is available ? HERE ? and includes a very simple use-case.
In order to use the Mex file, change you Matlab’s directory to the one containing the .mexw64 file and just call it as a standard function. In case our project’s name is “LoveMatlab” for example, then you would use the following syntax: Res = LoveMatlab(Input). Most common mistake during compilation is actually changing the above properties for a different build! In case it did not compiled, then check that you are editing corrent build: [RELEASE / DEBUG] & [x86 / x64].