Copying dynamic array to MxArray object using memcpy in c++
이전 댓글 표시
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?
채택된 답변
추가 답변 (1개)
댓글 수: 4
James Tursa
2012년 6월 28일
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
2012년 6월 28일
Abigail Cember
2017년 8월 23일
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
2017년 8월 23일
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.
카테고리
도움말 센터 및 File Exchange에서 C Shared Library Integration에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!