how to pass 2D array from c++ to matlab via mex new c++ api

19 visualizzazioni (ultimi 30 giorni)
Hi, i am trying to understand how to cast matlab variables and c++ variables
lets say i want to pass matrix i created in c++ (2D or 1D float array) to matlab.
i am using the new C++ api
i have tried something like:
CMatrixType2D<float> m_mfImage; //create matrix
m_mfImage.Init(m_Alg.mConfig.uiHeight, m_Alg.mConfig.uiWidth);//init matrix
aOutput.m_pmuiImage = &m_mfImage;
//Execute Algorithm
m_Alg.Execute(&aInput, &aOutput);//create frame output
outputs[0] = factory.createArray<float>({ m_Alg.mConfig.uiHeight , m_Alg.mConfig.uiWidth }, aOutput.m_pmuiImage);
but i cant figure how to convers/cast TypedArray to cpp array or get a pointer to work with.

Risposte (1)

Zehui Lu
Zehui Lu il 31 Mar 2020
I'm using Savyasachi Singh's template here to get the pointer of a TypedArray. Then I map this pointer to an Eigen matrix for the heavy computation. The example is like the following. Note that to use external c++ libraries with C++ MEX API, we need to write a wrapper (e.g. compute_something_with_eigen.cpp), and operator() can internally use this function. After we finish the computation with external libraries, we can find the pointer of this result matrix and map it back to a TypedArray.
// Assign the input, assume it's a 2D matrix
TypedArray<double> matrix = std::move(inputs[0]);
// Use the template I mentioned above
double* ptr = getPointer(matrix);
// Get the dimension of input
size_t size_input = matrix.getDimensions();
// Don't do the following in your C++ MEX main file
MatrixXd mat_eig = Map<MatrixXd>(ptr,size_input[0],size_input[1]);
// Do your algorithm

Prodotti


Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by