从c++ MEX文件返回值到MATLAB



我正在编写一个MATLAB程序,从c++代码检索数据。为此,我在MATLAB中创建了一个mexx文件和一个网关mexFunction。虽然读取值可以在MATLAB中读取,但我无法检索它以使用它。如果这是不清楚的,我有完全相同的问题(如何从mex函数返回一个浮点值,以及如何从m-file检索它?),但我想检索我的c++程序显示的值。下面是我的c++代码:

#define _AFXDLL
#define  _tprintf mexPrintf
#include "StdAfx.h"
#include "704IO.h"
#include "Test704.h"
#include "mex.h"
#ifdef _DEBUG
  #define new DEBUG_NEW
#endif
/////////////////////////////////////////////////////////////////////////////
CWinApp theApp;  // The one and only application object
/////////////////////////////////////////////////////////////////////////////
using namespace std;
/////////////////////////////////////////////////////////////////////////////
int _tmain(int argc, TCHAR *argv[], TCHAR *envp[])
//void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
HMODULE hModule(::GetModuleHandle(NULL));
short   valueRead;
  if (hModule != NULL)
  {
    // Initialize MFC and print and error on failure
    if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
    {
      //mexPrintf("Fatal Error: MFC initialization failed");
      //nRetCode = 1;
    }
    else
    {
        valueRead = PortRead(1, 780, -1);
        mexPrintf("Value Read = %in",valueRead);
    }
  }
  else
  {
    _tprintf(_T("Fatal Error: GetModuleHandle failedn"));
  }
  //return nRetCode;
}
/////////////////////////////////////////////////////////////////////////////
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    _tmain(0,0,0);
    return;
}
如果您需要关于我的问题的进一步信息,请告诉我。

要返回一个整数到Matlab,您可以遵循您发布的链接的说明,但修改它一点,以便返回整数。

void mexFunction(int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[])
{
    // Create a 1-by-1 real integer. 
    // Integer classes are mxINT32_CLASS, mxINT16_CLASS, mxINT8_CLASS
    // depending on what you want.
    plhs[0] = mxCreateNumericMatrix(1, 1, mxINT16_CLASS, mxREAL);

    // fill in plhs[0] to contain the same as whatever you want 
    // remember that you may want to change your variabel class here depending on your above flag to *short int* or something else.
    int* data = (int*) mxGetData(plhs[0]); 
    // This asigns data the same memory address as plhs[0]. the return value
    data[0]=_tmain(0,0,0); //or data[0]=anyFunctionThatReturnsInt();
    return;
}

最新更新