Help calling a matlab function in a mex function
显示 更早的评论
EDIT: See my answer below for clarification.
I want to modify sincall example to make it display besselj(0,x)
#include "matrix.h"
#include <string>
#include "mex.h"
#define MAX 1000
/* subroutine for filling up data */
void fill( double *pr, mwSize *pm, mwSize *pn, mwSize max )
{
mwSize i;
/* you can fill up to max elements, so (*pr)<=max */
*pm = max/2;
*pn = 1;
for (i=0; i < (*pm); i++)
pr[i]=i*(4*3.14159/max);
}
/* gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
mwSize m, n, max=MAX;
mxArray *rhs[2], *lhs[1];
mxArray *inplot[2]; /* input to plot function */
// (void) nlhs; (void) plhs; /* unused parameters */
// (void) nrhs; (void) prhs;
rhs[0]=0;
mxSetM(rhs[0], 1);
mxSetN(rhs[0], 1);
rhs[1] = mxCreateDoubleMatrix(max, 1, mxREAL);
/* pass the pointers and let fill() fill up data */
fill(mxGetPr(rhs[1]), &m, &n, MAX);
mxSetM(rhs[1], m);
mxSetN(rhs[1], n);
inplot[0] = mxDuplicateArray(rhs[1]);
/* get the sin wave */
std::string func=mxArrayToString(prhs[0]);
mexCallMATLAB(1, lhs, 2, rhs, func.c_str());
inplot[1] = mxDuplicateArray(lhs[0]);
/* plot(rhs, sin(rhs)) */
mexCallMATLAB(0, NULL, 2, inplot, "plot");
/* cleanup allocated memory */
mxDestroyArray(rhs[0]);
mxDestroyArray(lhs[0]);
mxDestroyArray(inplot[0]);
mxDestroyArray(inplot[1]);
return;
}
This makes matlab crash due to segmentation fault.
I would also like to learn why we set max to 1000 then divide it by 2. We first create an array of 1000 doubles, and then ignore the last 500? Is the last 500 also freed when we destroy array?
采纳的回答
更多回答(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!