How can a MEX file give parameters to a C++ program?
Show older comments
Hello!
I am coding a program in MATLAB, in which I have to call a C++ library. To do so, I created a C++ file that calls the library and then a MEX-file that help me to call the desired function in MATLAB. The function I want to access in the library returns me a value, but I have to give it parameters. I am currently able to retrieve a value, because I write my parameteres directly in the C++ code as you can see here (my file's name is Test704()):
// Test704.cpp : Defines the entry point for the console application.
#define _AFXDLL
#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[])
{
double valueRead;
//short port;
//short rack;
//short offset;
// valueRead = PortRead(1, 780, -1);
valueRead = PortRead(port[0], rack[0], offset[0]);
mexPrintf("Value Read = %i\n",valueRead);
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);
return ;
}
You will notice that I have commented parts of the code in order to make researches. Indeed, I want now to be able to give parameters by this way (MATLAB code):
x = 1;
y = 780;
z = 1;
myVal = double(Test704(x,y,z));
and to still be able to retrieve a value in myVal. I helped myself with the example timestwo.c provided by MathWorks, but unfortunately, it just returns me a value of 0 instead of 2 or 4, and I cannot figure out why.
Thanks for help,
Mana
Accepted Answer
More Answers (0)
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!