How to Convert a function return is a Handle (C++ mex)

Hi, I'm new to Matlab and looking for an example which demonstrates how to convert a function return is a Handle. (c++ mex)
C header, two function :
typedef void * DEVICE_HANDLE
DEVICE_HANDLE FUNC_CALL ZCAN_OpenDevice (UINT device_type, UINT device_index, UINT reserved);
mex:
void mexFunction(int nlhs,mxArray *plhs[],int nrhs, const mxArray *prhs[])
{
typedef void * DEVICE_HANDLE;
void *A;
unsigned int C;
if( nrhs != 3)
{
mexErrMsgTxt("MEXCPP requires 3 input arguments.");
return;
}
nlhs=1;
unsigned int p1 = mxGetScalar(prhs[0]);
unsigned int p2 = mxGetScalar(prhs[1]);
unsigned int p3 = mxGetScalar(prhs[2]);
mexPrintf("%s%d\t%s%d\t%s%d\n", "P1: ", p1, "P2 :", p2,"P3 :",p3);
plhs[0] = mxCreateNumericMatrix(1,1,mxUINT32_CLASS,mxREAL);
A = (unsigned int *) mxGetPr(plhs[0]);
C = (unsigned int)ZCAN_OpenDevice(p1,p2,p3);
mexPrintf("%s%d\n", "return: ", C);
A =C;
}

2 件のコメント

James Tursa
James Tursa 2020 年 1 月 9 日
Please provide more details of what you are trying to do.
huachun chen
huachun chen 2020 年 1 月 10 日
Hi,James. I've added some descriptions, trying to return a void pointers from mex functions.

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

回答 (1 件)

James Tursa
James Tursa 2020 年 1 月 10 日
編集済み: James Tursa 2020 年 1 月 10 日

0 投票

DEVICE_HANDLE is a pointer, so if you are running 64-bit MATLAB then DEVICE_HANDLE will be be 64-bits and will not fit in a 32-bit unsigned int. Thus it seems that your code will lose information when you do the (unsigned int) cast.
To return the value of the (void *) back to MATLAB you could do something like this:
union { void *A;
unsigned long long u;
} Au;
unsigned long long *A;
:
plhs[0] = mxCreateNumericMatrix(1,1,mxUINT64_CLASS,mxREAL);
A = (unsigned long long *) mxGetData(plhs[0]);
Au.A = ZCAN_OpenDevice(p1,p2,p3);
*A = Au.u;
But that begs the question, what are you intending to do with this pointer at the MATLAB level? I strongly suspect that you still have some fundamental design issues with your code that will lead to a crash.

1 件のコメント

huachun chen
huachun chen 2020 年 1 月 14 日
Thank you for your reply, James.
It doesn't worked , I've tried to use the Load Library method, which is more concise, and work well.

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

カテゴリ

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

製品

リリース

R2012b

タグ

質問済み:

2020 年 1 月 8 日

コメント済み:

2020 年 1 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by