我正在编写一个从 C++ 代码中检索数据的 MATLAB 程序。为此,我在 MATLAB 中创建了一个 MEX 文件和一个网关 mexFunction。
虽然可以在 MATLAB 中读取读取值,但我无法检索它来使用它。如果不清楚,我有与这里完全相同的问题(如何从 mex 函数返回浮点值,以及如何从 m 文件检索它? https://stackoverflow.com/questions/5943953/how-to-return-a-float-value-from-a-mex-function-and-how-to-retrieve-it-from-m-f)但我想检索我的 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 = %i\n",valueRead);
}
}
else
{
_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
}
//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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)