Passing const mxArray *prhs[i] to a function gives wrong values.
Mostrar comentarios más antiguos
Hello, I am currently writing a c++ mexFunction called by Matlab2017b. I work on a Linux machine, compiling mex with g++ gnu4.9.5.
I have more than 10 different prhs to read, and each prhs[] is copied to a struct class named Data.
In the following example, I am trying to fill the Data->XR Member. When declared in my Matlab script, XR = (0:95)*0.295e-3. However, when printing values from the MEX, I get crazy low values like 6.94882e-310.
Below is a simplified version of my code showing: the main, the function called and the class that needs to be filled.
#include <iostream>
using namespace std;
void
mexFunction (int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
Input_st *Data;
Data = new Input_st;
if (nrhs !=2) mexErrMsgIdAndTxt("Main:Input", "Number of Inputs must be 2");
int Counter = 0;
// Calling function that fills XR and NR
Data->NR = FillDataFromMxArray(Data->XR, prhs[Counter]); Counter++;
// Printing values for checking...
for (int i = 0 ; i < Data->NR ; i++)
{
cout << i << " " << Data->XR[i] << endl;
}
delete [] Data;
}
int
FillDataFromMxArray(double *pData, const mxArray *pMxArray)
{
const mwSize *pMxArrayDims;
double *pMxData;
// Check the number of elements.
pMxArrayDims = mxGetDimensions(pMxArray);
if (pMxArrayDims[0]!=1 || pMxArrayDims[1] <=0)
{
mexErrMsgIdAndTxt("FillPointerFromMxArray:Input",
"Argument with Array must be 1*N mxArray");
}
// Reading pointer to the first block of mxArray.
pMxData = (double*)mxGetData(pMxArray); //tried also with pMxData = mxGetPr(pMxArray)
pData = pMxData;
return (int)pMxArrayDims[1];
}
typedef struct Input_st {
double NR, *XR;
};
NR is correctly written but Not XR. FYI, before I was filling the Input_st directly the same way in the main/mexFunction (No FillDataFromMxArray) and values were correct.. So I am thinking it maybe because the prhs[Counter] is not passed properly.
Thanks in advance for your help, I hope everything is clear enough!
Pierre
2 comentarios
Guillaume
el 25 de Sept. de 2018
First thing, the argument you're saying is not passed properly is the 1st argument to the mex function? Your code imply that counter should be in a loop but it's not there, so you're only reading the 1st argument.
Secondly, is the passed data actually of type double?
Probably not relevant to your question but your dimension check is a bit flawed. It will accept a 1x1xN array and should return the values correctly, however the returned size (NR) will be incorrect.
Pierre Clouzet
el 25 de Sept. de 2018
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!