【发布时间】:2015-07-31 10:09:38
【问题描述】:
我是新来的,所以我会尝试清楚地揭露我的问题: 我目前正在用 MATLAB 语言开发一个程序,该程序必须加载一个库才能正常工作。但是,后者是用 C/C++ 编写的(我无法访问它),但我可以用 C++ 调用它,然后创建一个 MEX 文件以使用返回值。 使用 Visual Studio 2012,我成功地调用了该库(当我给它参数值作为参数时,portRead 函数返回一个值)。这是我的代码:
// Test704.cpp : Defines the entry point for the console application.
#define _AFXDLL
#define _tprintf mexPrintf
//#include "afx.h"
#include "StdAfx.h"
#include "704IO.h"
#include "Test704.h"
//#include "mat.h"
#include "mex.h"
//mxArray *matGetNextVariable(MATFile *mfp, const char **name);
#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[])
{
//int nRetCode(0);
HMODULE hModule(::GetModuleHandle(NULL));
short valueRead;
if (hModule != NULL)
{
// Initialize MFC and print and error on failure
if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
{
//_tprintf(_T("Fatal Error: MFC initialization failed\n"));
//mexPrintf("Fatal Error: MFC initialization failed");
//nRetCode = 1;
}
else
{
while(true)
{
valueRead = PortRead(1, 780, -1);
_tprintf(_T("Value Read = %i\n"), valueRead);
//mexPrintf("Value Read = %i",valueRead);
Sleep(1000); // Sleep for 1s so we can see the value on the screen
}
}
}
else
{
_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
//mexPrintf("Fatal Error: GetModuleHandle failed");
// nRetCode = 1;
}
//return nRetCode;
}
/////////////////////////////////////////////////////////////////////////////
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
int _tmain();
//short valueRead;
//valueRead = PortRead(1, 780, -1);
//_tprintf(_T("Value Read = %i\n"), valueRead);
//mexPrintf("Value Read = %i",valueRead);
return;
}
您可以看到我评论了我未成功的研究以解决我的问题... 此代码在控制台中返回“valueRead = 255”,这意味着程序运行良好。我现在想要的是在 MATLAB 中检索这个值。您可能还注意到我创建了一个 mexFunction;事实上,我阅读了文档,说明必须在 C++ 中创建通往 MATLAB(=mexFunction)的网关。
现在,我使用 MATLAB R2015a 创建了以下 MEX 文件:
function test()
location = 'C:\Users\admin\Documents\MATLAB\';
mylib = [location '704IO.lib'];
mex( 'Test704.cpp', mylib)
我没有检索“valueRead”,而是有一条消息表明
>Building with 'Microsoft Visual C++ 2012'. MEX completed successfully
所以,总而言之,我有功能性 C++ 代码,但我无法弄清楚为什么我无法将它链接到 MATLAB 以使用它!几天来我一直在寻找解决方案,我认为是时候寻求帮助了:)
非常感谢您的帮助! (P.-S.:我是 C++ 的初学者,很抱歉造成误解/语法错误)
【问题讨论】:
标签: c++ matlab visual-studio-2012 mex