Skip to content

C++ MEX files

Nexus loads MEX files that MATLAB built against its C++ interface (matlab::mex::Function and the matlab::data array classes) as they are, next to the C MEX files it already runs. You do not recompile them. This page lists what is supported and where the behaviour differs. Tracking: nexus#1225 (implementation) and nexus#1234 (remaining gaps).

What is supported

How it works

A C++ MEX file contains the C++ classes itself and calls the host through plain C functions (get_function_ptr, cppmex_*, mexApi*). Nexus provides those functions in libnexusmex. The loader notices the file's mexCreateMexFunction and mexFunctionAdapter entries, and calls the adapter in place of the empty C mexFunction the file also exports. Arguments are converted to the data-array form on the way in and back on the way out. On Linux the install carries empty libMatlabDataArray.so, libMatlabEngine.so, libmx.so, libmex.so and libmat.so in lib/nexus/<version>/mexcompat; they only make the names the file depends on resolve to libnexusmex.

Differences from MATLAB

The behaviours above that match MATLAB are those the test file test/mex/mexcompat-cpp-api.tst checks: its expected values were produced by running the same fixtures under MATLAB R2026a.

Writing your own C++ MEX file

Nexus ships a clean-room header set for the same public names (mex.hpp, mexAdapter.hpp, MatlabDataArray.hpp, MatlabEngine.hpp) under include/nexus/cppmex. nexus-mex file.cpp adds that directory to the include path, compiles as C++17, and links libnexusmex plus mexfilerequiredapiversion.cpp. A MATLAB-built C++ MEX still loads without a rebuild; the headers are for building one against Nexus. ArrayFactory::createEnumArray and EnumArray store the class and member names; Nexus resolves them when the array is returned, so an unknown class or member fails at that point, as the cppmex_idiom_data enum commands expect. ObjectArray and ArrayFactory::createObjectArray wrap the object-array table entries (ids 120–127). The headers were written from Nexus's own function table, not from MathWorks header source. The older MATLAB-only rebuild of the test fixtures remains test/mex/build-cppmex-fixtures.sh. For C code written against mex.h use nexus-mex, as described on the Toolboxes page.

Example sources

Small, commented C++ MEX examples are in the repository under examples/cpp-mex/:

Troubleshooting