If I have a pointer *ptr that is pointing to a 2-D array of UINT16 type in C++, what code in a CMEX file will convert that data to a mxArray that can be output to MATLAB? Ultimately what I want is a myfunction.mexw64 file where Z = myfunction executed in MATLAB provides the original 2-D array that I have right now in C++.

 採用された回答

James Tursa
James Tursa 2014 年 5 月 30 日
編集済み: James Tursa 2014 年 5 月 30 日

1 投票

If the array elements are in column order in the C++ file, then a simple copy will suffice. E.g.,
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
unsigned short *pr;
unsigned short ptr[] = {1,2,3,4,5,6};
mwSize i, m = 2, n = 3, mn = m*n;
plhs[0] = mxCreateNumericMatrix(m,n,mxUINT16_CLASS,mxREAL);
pr = mxGetPr(plhs[0]);
for( i=0; i<mn; i++ ) {
pr[i] = ptr[i];
}
}
In the above code I have used an array for ptr for simplicity, but a pointer to a block of memory will work just as well.
If the elements are in row order instead of column order, a transpose will be involved. If that is the case, let me know and I will post that code. (Or you can just transpose it at the MATLAB level)

2 件のコメント

Robert Hinkey
Robert Hinkey 2014 年 5 月 30 日
編集済み: Robert Hinkey 2014 年 5 月 30 日
Thanks James. One small adjustment is needed, the line:
pr = mxGetPr(plhs[0]);
should read:
pr = (unsigned short*)mxGetData(plhs[0]);
since the mxGetPr is for type double only. The original line maybe works for some people, but my Visual C++ 2008 compiler doesn't like it.
James Tursa
James Tursa 2014 年 5 月 30 日
編集済み: James Tursa 2014 年 5 月 30 日
Correct. I had modified some double code that I already had and missed that. Thanks.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeWrite C Functions Callable from MATLAB (MEX Files) についてさらに検索

タグ

質問済み:

2014 年 5 月 30 日

編集済み:

2014 年 5 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by