【发布时间】:2023-03-05 18:56:01
【问题描述】:
我正在编写一个从 C++ 代码中检索数据的 MATLAB 程序。为此,我在 MATLAB 中创建了一个 MEX 文件和一个网关 mexFunction。 尽管可以在 MATLAB 中读取读取的值,但我无法检索它来使用它。如果不清楚,我的问题与此处 (How to return a float value from a mex function, and how to retrieve it from 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 = %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;
}
如果您需要有关我的问题的更多信息,请告诉我?
【问题讨论】:
-
在您发布的链接中,答案非常好,尽其所能。有什么问题?
-
这确实非常好,但对我来说不合适:我想从 _intmain() 中检索值,它应该读取设备的输出和更改。在我发布的链接中给出的解决方案中,该值在代码中“几乎”给出,我不希望这样。
-
你几乎是什么意思?它只是一个数字,你也可以这样做。而不是
data[0] = 1;,请执行data[0]=_tmain(0,0,0)(或您想要返回的任何其他值)。 -
对我来说几乎不意味着该值包含在代码中。我已经尝试过
data[0]=_tmain(0,0,0),但它只是返回值 0 而 Test704() 的返回值为 1。 -
然后给我们看代码!您需要显示所有代码,否则我们无法帮助您!您显示的代码中没有
Test704(),您也没有尝试返回任何值!