Determine Path of Mex S function from the C/C++ mex code

5 views (last 30 days)
I have a C++ level 2 S function that I am compiling with mex. This s function loads data from external files that are located relative to the s function file itself. Say, the data is located at "..\data" relative to the s function file itself (say it is myFunction.mexw32). Is is it possible from my C++ code to determine the path the S function so that I can then determine the location of my data files? I know this is possible in a script using the mfilename('fullpath') method, but I can't find how to do it in an S function.
I really really don't want to hard code the path to the data as that will cause other issues. If I leave it relative it looks it up relative to MATLAB's current directory, not the directory of the S function (which is located elsewhere on MATLAB's path).
Thanks for any help!

Accepted Answer

Kaustubha Govind
Kaustubha Govind on 9 May 2013
In MATLAB, you can look up the full path to any given file using the MATLAB function which. You can call this from your S-function using mexCallMATLAB, with the S-function name passed in as the input argument. Note that the S-function name is stored in the macro S_FUNCTION_NAME which is defined at the top of every S-function.

More Answers (2)

Graham Fletcher
Graham Fletcher on 17 Feb 2020
I realise this is quite old, but this can be achieved without needing to call back into Matlab. On Windows, I use
GetModuleHandleEx
and
GetModuleFileName
in conjunction to get the path to the mexw64.See this StackOverflow post for a fuller description.

Ben
Ben on 10 May 2013
A little bit roundabout, but it works great. Thanks!

Categories

Find more on Simulink Coder in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!