MATLAB crashes when I use a mex function that uses a c++ class

I wrote a cpp wrapper for A class I would like to use in MATLAB, but when I specifcally use the add() function it causes a crash, here is the wrapper file with the relevant functions:
#include "mex.h"
#include "pdqForMatrix.h"
// This program works as the translator between MATLAB and C++. It uses the priority_deque class (in the PDQHeap.h file) and the mex.h library to create a MEX file that can be used in MATLAB.
priority_deque<std::pair<double, std::vector<std::vector<double>>>> *pq = NULL;
// The gateway function
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Check for proper number of arguments
// if(nrhs < 1) {
// mexErrMsgIdAndTxt("PriorityDeque:nrhs", "At least one input required.");
// }
// Command string
char *command = mxArrayToString(prhs[0]);
// Initialize, e.g: pq_ptr = priority_deque_mex('init')
if(strcmp(command, "init") == 0) { //strcmp returns 0 if the two strings are equal
// Create a priority_deque instance and store the pointer in plhs[0]
pq = new priority_deque<std::pair<double, std::vector<std::vector<double>>>>();
plhs[0] = mxCreateNumericMatrix(1, 1, mxINDEX_CLASS, mxREAL);
memcpy(mxGetData(plhs[0]), &pq, sizeof(pq));
return;
}
// Get the priority_deque instance
if(nrhs > 1) {
memcpy(&pq, mxGetData(prhs[1]), sizeof(pq));
}
// Add, e.g : priority_deque_mex('add', pq_ptr, value)
if(strcmp(command, "add") == 0) {
if(nrhs != 3) {
mexErrMsgIdAndTxt("PriorityDeque:nrhs", "Three inputs required.");
}
std::pair<double, std::vector<std::vector<double>>> input;
// Accessing the first element of the cell array (double)
mxArray *cellElement1 = mxGetCell(prhs[1], 1);
double value = mxGetScalar(cellElement1);
input.first = value;
// Accessing the second element of the cell array (vector<vector<double>>)
mxArray *cellElement2 = mxGetCell(prhs[1], 2);
// Get the number of elements in the second element cell array
mwSize numRows2 = mxGetNumberOfElements(cellElement2);
std::vector<std::vector<double>> pair;
// Iterate over the second element cell array
for (mwSize i = 0; i < numRows2; ++i) {
mxArray *innerCell = mxGetCell(cellElement2, i);
double *data = mxGetPr(innerCell);
mwSize numRowsInner = mxGetM(innerCell);
mwSize numColsInner = mxGetN(innerCell);
// Convert the inner cell array to vector<double>
std::vector<double> innerVec;
for (mwSize j = 0; j < numRowsInner * numColsInner; ++j) {
innerVec.push_back(data[j]);
}
// Add the inner vector to the main pair
pair.push_back(innerVec);
}
input.second = pair;
pq->add(input);
return;
}
// Poll e.g : priority_deque_mex('poll', pq_ptr) gpt
if (strcmp(command, "poll") == 0) {
if (nlhs != 1) {
mexErrMsgIdAndTxt("PriorityDeque:nlhs", "One output required.");
}
std::vector<std::vector<double>> result = pq->poll().second;
mwSize numRows = result.size();
mwSize numCols = (numRows > 0) ? result[0].size() : 0;
// Create a MATLAB matrix to store the result
mxArray* output = mxCreateDoubleMatrix(numRows, numCols, mxREAL);
double* outputData = mxGetPr(output);
// Copy the data from the result vector<vector<double>> to the MATLAB matrix
for (mwSize i = 0; i < numRows; ++i) {
for (mwSize j = 0; j < numCols; ++j) {
outputData[i + j * numRows] = result[i][j];
}
}
plhs[0] = output;
return;
}
// Poll e.g : priority_deque_mex('peek', pq_ptr) gpt
if (strcmp(command, "peek") == 0) {
if (nlhs != 1) {
mexErrMsgIdAndTxt("PriorityDeque:nlhs", "One output required.");
}
std::vector<std::vector<double>> result = pq->peek().second;
mwSize numRows = result.size();
mwSize numCols = (numRows > 0) ? result[0].size() : 0;
// Create a MATLAB matrix to store the result
mxArray* output = mxCreateDoubleMatrix(numRows, numCols, mxREAL);
double* outputData = mxGetPr(output);
// Copy the data from the result vector<vector<double>> to the MATLAB matrix
for (mwSize i = 0; i < numRows; ++i) {
for (mwSize j = 0; j < numCols; ++j) {
outputData[i + j * numRows] = result[i][j];
}
}
plhs[0] = output;
return;
}
// Deallocate e.g : priority_deque_mex('delete', pq_ptr)
if(strcmp(command, "delete") == 0) {
delete pq;
return;
}
}
EDIT:
Here is the code where I call the function and the crash happens:
pdq = wrapperPDQ('init')
pair = {4, [4; 5; 6]}
%wrapperPDQ('add', pdq, pair)
a = wrapperPDQ('poll', pdq)
wrapperPDQ('delete', pdq)

3 个评论

the main reason why matlab might get crashed is:-
1} memory management errors
2} noncompatibel datatypes used in code
3} not using mex API accurately
SOLUTIONS
to check memory management errors use the command valgrind
HERE I HAVE PROVIDED LINKS TO CHECK OUT FOR SOLUTIONS FOR REFERANCE
There are a LOT of places where this code can go wrong. You need to put in checks on all the inputs for type, size, complexity, sparsity, etc. to make sure your code is robust. Until you do this, it is not worth digging into your code for logic errors.
The problem turned out to be due to be an indexing problem for which parameter of the input I deal with, thank you for your insight.

请先登录,再进行评论。

回答(1 个)

The main reason why matlab might get crashed is:-
1} memory management errors
2} noncompatibel datatypes used in code
3} not using mex API accurately
SOLUTIONS
to check memory management errors use the command valgrind
HERE I HAVE PROVIDED LINKS TO CHECK OUT FOR SOLUTIONS FOR REFERANCE

1 个评论

The problem turned out to be due to an indexing problem for which parameter of the input I deal with, thank you for your insight.

请先登录,再进行评论。

类别

在 帮助中心 和 File Exchange 中查找有关 Function Creation 的更多信息

产品

版本

R2022b

标签

Community Treasure Hunt

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

Start Hunting!

Translated by