Handling Inputs mex function

2 Ansichten (letzte 30 Tage)
Steven Huynh
Steven Huynh am 31 Mär. 2021
Kommentiert: Steven Huynh am 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

Akzeptierte Antwort

James Tursa
James Tursa am 31 Mär. 2021
Bearbeitet: James Tursa am 31 Mär. 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.

Weitere Antworten (0)

Kategorien

Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by