Problem in using mxSetPr with USHORT

3 views (last 30 days)
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.

Accepted Answer

Jan
Jan on 17 Feb 2022
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.

More Answers (1)

James Tursa
James Tursa on 18 Feb 2022
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 Comments
Jan
Jan on 18 Feb 2022
Thanks for you explanations.

Sign in to comment.

Categories

Find more on MATLAB Compiler in Help Center and File Exchange

Tags

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!