MATLAB Answers

How to write a C++ program to test dlls generated by Matlab compiler

25 views (last 30 days)
Sandy on 22 Sep 2015
Edited: Oindri on 14 Mar 2018
I have a Matlab function and have already compiled it into dll file so that my coworkers can use it in C++.
I would like to test the dll files before I send them out. However, first I cannot test them by using "loadlibrary" due to its limitations. Second, I have no ability to write a cpp program in Microsoft visual studio to test.
Does anyone can help me out here? I was thinking that I can run the "xxxx.cpp" directly in Microsoft visual studio to test whether the dll files work. But things seem to be much more complicated than what I thought.
Is there any simply way to solve this problem? Any suggestions are appreciated.

Answers (1)

Oindri on 14 Mar 2018
Edited: Oindri on 14 Mar 2018
mwArray class is the simplest to use and to make understand. I am assuming you have an array type input and will be obtaining an array type output. create this application file. use mbuild on command prompt to build solution for the project by calling mbuild app.cpp filename.dll
// Include the C++ shared library header #include "filename.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( !filenameInitialize() )
std::cerr << "could not initialize the library properly"
<< std::endl;
return -1;
// Create input data, operation to be applied on in, of type datatype, / //let's assume an array of size m*n
datatype data[] = {m+n};
mwArray in(m, n, mxDOUBLE_CLASS, mxREAL);
in.SetData(data, m+n);
// Create output array, obtained post applying filename function on 'in'.
mwArray out;
// Call the library function
filename(1, out, in);
std::cout << "The answer 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
// Release all state and resources used by the MATLAB Runtime for the application
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);
once the solution is built error free, you may run the executable.


Sign in to comment.

Translated by