Copying dynamic array to MxArray object using memcpy in c++
Show older comments
I am writing a c++ program that calls that Matlab Engine. I am getting an error when I try to use memcpy for a dynamically allocated multi-dimensional array. I have a type definition as follows in my header file:
typedef double* dblArrayptr;
My array definition in my function is as as follows:
dblArrayptr *A;
A = new dblArrayptr [2*NUMROWS];
for (int i=0;i<2*NUMROWS;i++)
A[i] = new double [2*NUMROWS];
I initialize this matrix A with some values and then try to use the memcpy command as follows: (note: this matrix has 44 rows and 44 columns).
memcpy((void *)mxGetPr(A_m), (void *)A,1936*sizeof(double));
I receive a memory access violation error. Access violation reading location.
This memcpy command seems to work ok if I have a single array (44x1) of type double.
Do I have to do an element by element copy?
Accepted Answer
More Answers (1)
4 Comments
James Tursa
on 28 Jun 2012
You misunderstand me. None of the solutions I proposed require recompiling each time a new size is used. All of them allocate memory at runtime to handle any size they need. The basic outline I would suggest is something like this (assuming you still want the column pointers in A for some reason):
mxArray *mx;
double **A;
mwSize i;
mx = mxCreateDoubleMatrix(2*NUMROWS, NUMCOLUMNS, mxREAL);
A = (double **)mxMalloc(NUMCOLUMNS*sizeof(*A));
A[0] = mxGetPr(mx);
for( i=1; i<NUMCOLUMNS; i++ ) {
A[i] = A[i-1] + 2*NUMROWS;
}
// work with A as needed
mxFree(A);
mxDestroyArray(mx);
Lauren
on 28 Jun 2012
Abigail Cember
on 23 Aug 2017
I know this question was asked a while ago, but I'll try my luck... Why was it necessary here to declare i as mwSize instead of int?
James Tursa
on 23 Aug 2017
It wasn't. int would have worked just as well. Having said that, there is a possible subtle issue depending on how NUMCOLUMNS is defined. If it is defined as mwSize, then it could end up being a size_t, which is unsigned. Then if i is an int, which is signed, you are mixing signed and unsigned integers in downstream code. Now this can be done correctly of course if you are careful, but it is something you as the programmer need to be aware of to make sure it is not an issue in your downstream code.
Categories
Find more on C Shared Library Integration in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!