繁体   English   中英

MEX文件如何为C ++程序提供参数?

[英]How can a MEX file give parameters to a C++ program?

我正在用MATLAB编写程序,其中必须调用C ++库。 为此,我创建了一个C ++文件,该文件调用该库,然后创建一个MEX文件,该文件可以帮助我在MATLAB中调用所需的函数。 我想在库中访问的函数返回一个值,但是我必须给它提供参数。 我现在能够检索一个值,因为我直接在C ++代码中编写了参数,如您在此处看到的那样(我的文件名为Test704()):

// Test704.cpp : Defines the entry point for the console application.
#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[])
int _tmain(double port[], double rack[], double offset[])
{
//HMODULE hModule(::GetModuleHandle(NULL));
double  valueRead;
//short port;
//short rack;
//short offset;

  //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"));
  //  }
  //  else
  //  {
  //    //while(true)
  //    //{
  //      valueRead = PortRead(1, 780, -1);
        valueRead = PortRead(port[0], rack[0], offset[0]);
        mexPrintf("Value Read = %i\n",valueRead);
  //      //Sleep(1);  // Sleep for 1s so we can see the value on the screen
  //    //}
  //  }
  //}
  //else
  //{
  //  _tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
  //}  
return valueRead;
}

/////////////////////////////////////////////////////////////////////////////
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    double *port, *rack, *offset;
    // Creates a 1-by-1 real integer. 
    //plhs[0] = mxCreateNumericMatrix(1, 1, mxINT32_CLASS, mxREAL);
    plhs[0] = mxCreateNumericMatrix(1, 1, mxINT32_CLASS, mxREAL);

    int* data = (int*) mxGetData(plhs[0]); 
    port = mxGetPr(prhs[0]);
    rack = mxGetPr(prhs[0]);
    offset = mxGetPr(prhs[0]);
    //valueRead = mxGetPr(plhs[0]);

    //data[0]=_tmain(0,0,0); 
    //return ;
    data[0] = _tmain(port,rack,offset);
}

您会注意到,我已经注释了部分代码以便进行研究。 确实,我现在希望能够通过这种方式提供参数(MATLAB代码):

x = 1;
y = 780;
z = 1;
myVal = double(Test704(x,y,z));

并仍然能够检索myVal中的值。 我通过MathWorks提供的示例timestwo.c帮助自己,但不幸的是,它无法正常工作,我也不知道为什么。

传递给mex函数的任何参数都可以通过使用int nrhs, const mxArray *prhs[]

根据参数的类型,您需要使用不同的功能。 例如,如果第一个参数是双精度型,则可以这样检索:

double p = mxGetScalar(prhs[0]);

http://de.mathworks.com/help/matlab/access-data.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM