Handling Inputs mex function
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Steven Huynh
le 31 Mar 2021
Commenté : Steven Huynh
le 1 Avr 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
0 commentaires
Réponse acceptée
James Tursa
le 31 Mar 2021
Modifié(e) : James Tursa
le 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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Write C Functions Callable from MATLAB (MEX Files) dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!