Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations cowski on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

create dll with mex, and output structure

Status
Not open for further replies.

shetlandbob

Aerospace
Joined
Jul 6, 2005
Messages
2
Location
GB
Hi folk!

Thanks for taking time to read this. I am trying to create a dll in Matlab 6.5.1.199709 (R13) Service Pack 1

I've reduced it down to a smaller example:
Code:
#include "mex.h"

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
  char**   fnames;
  char*    pText;
  char*    buf;
  char*    pData;
  char     text[80][3];
  int      mrows,ncols,i,nfields,buflen;
  mxArray* array;
  size_t   sizebuf;
  double myData[10];
  
  nfields = 3;
  /* Check for proper number of arguments. */
  if(nrhs!=1) {    mexErrMsgTxt("One input required.");  } 
  else if(nlhs>1) { mexErrMsgTxt("Too many output arguments");  }
  
  /* The input must be a noncomplex scalar double.*/
  mrows = mxGetM(prhs[0]);
  ncols = mxGetN(prhs[0]);
  if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || !(mrows==1 && ncols==1) ) { mexErrMsgTxt("Input must be a noncomplex scalar double.");  }
  
  // Build Field Array Names;
  fnames = mxMalloc(nfields, sizeof(*fnames));
  for ( i = 0; i < nfields; i++ )
  {
    sprintf ( text[i], "F%i", i+1 );
    pText = text[i];
    fnames[i] = pText;
    printf ( "%i.%s\n", i+ 1, fnames[i] );
  }
  plhs[0] = mxCreateStructMatrix(1, 1, nfields, fnames);
  printf ( "Created Dummy Structure\n" );
  mxFree(fnames);
  
  array = mxCreateDoubleMatrix(1,5, mxREAL);
  for ( i = 0; i < 5; i++ ) myData[i] = i+0.1;
  mxSetPr(array, myData);
  mxSetM(array,1);
  mxSetN(array,5);

  mxSetFieldByNumber(plhs[0], 0, 0, array);
  mxSetFieldByNumber(plhs[0], 0, 1, array);
  mxSetFieldByNumber(plhs[0], 0, 2, array);

  printf ( "done\n" );
}
I'v searched the help/internet and cant see whats wrong with the code?
I compile and run with
Code:
mex test.c
text(1.1)
The output should be a structured array with 3 variables, each containing 5 elements.

It runs ok the first time I try to run it (90%), but subsequent runs it crashes and I have to exit matlab to get it to work again?

Any input/help much appreciated.

Thanks
 
return;


I also changed to

const char** fnames;

and also

fnames = mxCalloc(nfields, sizeof(*fnames));


but I think it was the return; as the inal insruction that did the trick.
 
Try running it more than once, close matlab open again and run without recompiling a number of times, I'll be surprised if it works.

Having said that the problem is fixed by using
Code:
mexMakeMemoryPersistent(array)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top