Handling Inputs mex function

2 views (last 30 days)
Steven Huynh
Steven Huynh on 31 Mar 2021
Commented: Steven Huynh on 1 Apr 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

Accepted Answer

James Tursa
James Tursa on 31 Mar 2021
Edited: James Tursa on 31 Mar 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.

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!