Problem in using mxSetPr with USHORT

조회 수: 1 (최근 30일)
Wang Yifan
Wang Yifan 2022년 2월 17일
댓글: Wang Yifan 2022년 2월 22일
I create an array in C, and the element of the array is USHORT, counting for 2 Bytes. Now, I wanna transfer this array to MATLAB workspace, using MATLAB-C API. The current method I used is to copy the value of each elements one by one in a for-loop. It is so inefficient. Therefore, I want to use pointers. However, I found the function mxSetPr demands the input type is double*. USHORT is determined by the hardware I used. Is there any similar function which can accomplish the address transformation from C to MATLAB workspace, and is valid for USHORT.

채택된 답변

Jan
Jan 2022년 2월 17일
Either use memcpy instead of copying the data in a loop.
Or use mxSetData instead of mxSetPr, if you are really sure, that the USHORT array is not released from anywhere else. But this is fragile: if the Matlab variable is deleted later, mxFree()'ing the data pointer might cause a crash. I'd prefer memcpy.

추가 답변 (1개)

James Tursa
James Tursa 2022년 2월 18일
To attach pointers of type other than double to an mxArray, you can use the mxSetData( ) function as Jan suggests. In your case you would create an mxArray of type mxUINT16_CLASS for this.
However, this will only work if the pointer was allocated with an official API function such as mxMalloc( ) or mxCalloc( ). If the pointer points to memory allocated by standard C/C++ routines such as malloc( ) or calloc( ), or the pointer points to local variables allocated off of the stack, then the use of mxSetData( ) with these pointers will result in an assertion fault and a MATLAB crash. In these cases, you must copy the data with a loop or memcpy( ).
  댓글 수: 4
Jan
Jan 2022년 2월 18일
Thanks for you explanations.
Wang Yifan
Wang Yifan 2022년 2월 22일
Thanks a lot.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 MATLAB Compiler에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by