AP - the documentation for mxSetPr indicates that for the second input parameter to this function,
The array must be in dynamic memory; call mxCalloc to allocate this memory. Do not use the ANSI® C calloc function, which can cause memory alignment issues leading to program termination. If pr points to static memory, memory leaks and other memory errors can result.
Did you use mxCalloc to allocate memory to Ain and kernel? That being said, I did try the following test function
mxArray* myMxArray = 0;
double* myDblArray = 0;
myMxArray = mxCreateNumericMatrix( 0, 0, mxDOUBLE_CLASS, mxREAL );
myDblArray = mxCalloc(4,sizeof(double));
if (myMxArray!=NULL && myDblArray!=NULL)
and the above crashed at the mxSetPr line. So I am a little puzzled by the above. James Tursa would most likely know what is wrong with the above code.
The only time I've seen mxSetPr being used in for output (the lhs) of the mexFunction, so if I had to do something similar to what you are doing, I would have tried the following
void myfun2(double *Ain , int AnRows , int AnCols,
double *kernel, int kernelnRows, int kernelnCols,
// create the mxArrays
rhs = mxCreateNumericMatrix( AnRows, AnCols, mxDOUBLE_CLASS, mxREAL );
rhs = mxCreateNumericMatrix( kernelnRows, kernelnCols, mxDOUBLE_CLASS, mxREAL );
rhs = mxCreateString ( "same" );
// copy the Ain and kernel data
ptr = mxGetPr(rhs);
ptr = mxGetPr(rhs);
mexCallMATLAB(1, lhs, 3, rhs, "conv2");
// destroy the mxArrays
Note in the above how memcpy is used to copy the data from the Ain and Kernel arrays to the destination mxArrays. Note also that for every create of an mxArray, we must destroy or free memory allocated to that array.
For the case of the left-hand side result of the convolution, we pass an mxArray into this function as
As (presumably) memory will be dynamically allocated to it within the conv2 function, the caller of myfun2 does not need to allocate memory to this parameter, but the caller will be responsible for freeing the memory. For example,
// do some work to create the Ain and Kernel matrices
// declare the output matrix from the 2D convolution
mxArray *convMtx = 0;
// call the function to do the 2D convolution
myfun2(Ain, AnRows, AnCols,kernel,kernelnRows,kernelnCols,&convMtx);
// do some stuff with convMtx
// destroy mxArray
See how we pass the convMtx into the function as &convMtx.