|
| 1 | +// C++ Matlab MEX function using C++17 <filesystem> |
| 2 | +// https://www.mathworks.com/help/matlab/matlab_external/data-types-for-passing-mex-function-data-1.html |
| 3 | + |
| 4 | +#include "mex.hpp" |
| 5 | +#include "mexAdapter.hpp" |
| 6 | + |
| 7 | +#include <string> |
| 8 | +// note: <string_view> causes compile failures with MSVC at least |
| 9 | + |
| 10 | +#include <vector> |
| 11 | +#include <memory> |
| 12 | + |
| 13 | +#if defined(_WIN32) |
| 14 | +#include "win32_fs.h" |
| 15 | +#endif |
| 16 | + |
| 17 | + |
| 18 | +class MexFunction : public matlab::mex::Function { |
| 19 | +public: |
| 20 | + void operator()(matlab::mex::ArgumentList outputs, matlab::mex::ArgumentList inputs) { |
| 21 | +// boilerplate engine & ArrayFactory setup |
| 22 | + std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine(); |
| 23 | + |
| 24 | + matlab::data::ArrayFactory factory; |
| 25 | +// boilerplate input checks |
| 26 | + if (inputs.size() != 1) { |
| 27 | + matlabPtr->feval(u"error", 0, |
| 28 | + std::vector<matlab::data::Array>({ factory.createScalar("One input required") })); |
| 29 | + } |
| 30 | + if (inputs[0].getType() != matlab::data::ArrayType::MATLAB_STRING) { |
| 31 | + matlabPtr->feval(u"error", 0, |
| 32 | + std::vector<matlab::data::Array>({ factory.createScalar("Input must be a string") })); |
| 33 | + } |
| 34 | + if (inputs[0].getNumberOfElements() != 1) { |
| 35 | + matlabPtr->feval(u"error", 0, |
| 36 | + std::vector<matlab::data::Array>({ factory.createScalar("Input must be a scalar string") })); |
| 37 | + } |
| 38 | + |
| 39 | +// Matlab strings are an array, so we use [0][0] to get the first element |
| 40 | + std::string inputStr = inputs[0][0]; |
| 41 | + |
| 42 | +// actual function algorithm / computation |
| 43 | +#if defined(_WIN32) |
| 44 | + std::string s = fs_shortname(inputStr); |
| 45 | +#else |
| 46 | + std::string s = ""; |
| 47 | +#endif |
| 48 | + |
| 49 | +// convert to Matlab output -- even scalars are arrays in Matlab |
| 50 | +// https://www.mathworks.com/help/matlab/matlab_external/create-matlab-array-with-matlab-data-cpp-api.html |
| 51 | +// https://www.mathworks.com/help/matlab/apiref/matlab.data.arrayfactory.html |
| 52 | + |
| 53 | + outputs[0] = factory.createScalar(s); |
| 54 | + } |
| 55 | +}; |
0 commit comments