Handling Inputs mex function

2 visualizaciones (últimos 30 días)
Steven Huynh
Steven Huynh el 31 de Mzo. de 2021
Comentada: Steven Huynh el 1 de Abr. de 2021
Hello, I need help to simply change the inputs "double/string" in the prhs[i] to int/char in mex function. As in the following code
//code works without use prhs[]
#include "mex.h"
#include <string.h>
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[]) {
char* serialNo = "5584112";
int N=5;
}
To something like (conversion errors)
//I want to use prhs[]
#include "mex.h"
#include <string.h>
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[]) {
char* serialNo;
int N;
serialNo = prhs[0];
N = prhs[1];
}
// Matlab command >> Mymexfunction("5584112",5)
// here "5584112" is a string type and 5 is a double
I tried to converted with type-casting or specific function in mex.h (like "int N = (int)mxGetPr(prhs[1]);") but I don't get what I want. Is it possible to converter like that? what should I do? Thank you

Respuesta aceptada

James Tursa
James Tursa el 31 de Mzo. de 2021
Editada: James Tursa el 31 de Mzo. de 2021
The prhs[ ] variables are of type pointer to mxArray ... you cannot use simple native C conversions with them. You must use some API functions for this. E.g., bare bones with no input argument checking:
#include "mex.h"
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
mxArray *mx;
char* serialNo;
int N;
mexCallMATLAB(1,&mx,1,(mxArray **)prhs,"char");
serialNo = mxArrayToString(mx);
mxDestroyArray(mx);
N = (int) mxGetScalar(prhs[1]);
// insert code here to use serialNo and N
mxFree(serialNo);
}
Side Note: You could have gotten your attempt at getting the integer to work if you had dereferenced the pointer from mxGetPr first. E.g.,
int N = (int)*mxGetPr(prhs[1]);
But the only way to get your C char string from a MATLAB string type is to use the mexCallMATLAB callback route as I have shown.

Más respuestas (0)

Categorías

Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by