Passing const mxArray *prhs[i] to a function gives wrong values.
显示 更早的评论
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 个评论
Guillaume
2018-9-25
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
2018-9-25
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Write C Functions Callable from MATLAB (MEX Files) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!