This example shows how to call a C++ shared library built with MATLAB® Compiler SDK™ from a C++ application.
Create a C/C++ shared library using a MATLAB function. For more information, see Create a C/C++ Shared Library with MATLAB Code.
Navigate to the for_testing
folder created when you generated the
C/C++ shared library.
Create a new file called addmatrix_app.cpp
.
Copy the following C++ code into the file and save it. This is the application that calls the C/C++ shared library.
// Include the C++ shared library header #include "addmatrix.h" int run_main(int argc, char **argv) { // Set up the application state for the MATLAB Runtime instance created in the application. if (!mclInitializeApplication(NULL,0)) { std::cerr << "could not initialize the application properly" << std::endl; return -1; } // Load the required MATLAB code into the MATLAB Runtime. if( !addmatrixInitialize() ) { std::cerr << "could not initialize the library properly" << std::endl; return -1; } try { // Create input data double data[] = {1,2,3,4,5,6,7,8,9}; mwArray in1(3, 3, mxDOUBLE_CLASS, mxREAL); mwArray in2(3, 3, mxDOUBLE_CLASS, mxREAL); in1.SetData(data, 9); in2.SetData(data, 9); // Create output array mwArray out; // Call the library function addmatrix(1, out, in1, in2); std::cout << "The value of added matrix is:" << std::endl; std::cout << out << std::endl; } // Catch the MATLAB generated mwException catch (const mwException& e) { std::cerr << e.what() << std::endl; return -2; } // Catch any other exceptions that may be thrown catch (...) { std::cerr << "Unexpected error thrown" << std::endl; return -3; } // Release the resources used by the generated MATLAB code addmatrixTerminate(); // Release all state and resources used by the MATLAB Runtime for the application mclTerminateApplication(); return 0; } int main() { // Initialize the MATLAB Runtime mclmcrInitialize(); // Create a new thread and run the MATLAB generated code in it. return mclRunMain((mclMainFcnType)run_main,0,NULL); }
Use the system's command line to navigate to the for_testing
folder
where you created addmatrix_app.cpp
.
Use mbuild
at the system's command line to compile and link the
application.
mbuild addmatrix_app.cpp addmatrix.lib
The .lib
extension is for Windows®. On Mac the file extension will be .dylib
, and on Linux® it will be .so
.
From the system's command prompt, run the application.
addmatrix_app The value of added matrix is: 2 8 14 4 10 16 6 12 18
To follow up on this example:
Try installing the new application on a different computer.
Try building an installer for the application.
Try integrating a shared library that consists of more than one function.