MATLAB: How to use STL containers in the C++ shared library

clibraryMATLAB Compilersharedstlvector

I would like to implement STL containers with my C++ shared library project, for example the STL vector, with the mwArray API. I want to do this for performance reasons.

Best Answer

You can use an STL container by copying it to a standard C++ array and then using the mwArray API. Below is an example of using a STL vector with the mwArray API.
#include "mclcppclass.h"
#include <vector>
int main(int argc, int **argv)
{
if (!mclInitializeApplication(NULL,0))
{ std::cerr << "could not initialize the library properly"<<std::endl;
return 1;
}
std::vector<double> B;
int arraysize;
int* A;
//use dynamic array allocation
A = new int[arraysize];
int a =2;
int b=-5;
//populate the vector
B.push_back(a);
B.push_back(b);
//copy the vector components to the dynamic array
std::copy(B.begin(), B.end(), A);
mwArray Y(2,1, mxDOUBLE_CLASS);
Y.SetData(A,2);
std::cout << Y << std::endl;
delete[] A;
B.clear();
return 0;
}
Then build the project in MATLAB
mbuild -v TestExample.cpp
!TestExample.exe
Related Question