How to decode mxGetData void pointer nicely
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I'm trying to write a C++ mex function that can handle multiple datatypes. So I do something like:
void *data = mxGetData(mxarray);
switch (mxGetClassID(mxarray)) {
case mxDOUBLE_CLASS:
my_function((double *) data);
...
my_function is templated, so this handles different datatypes nicely. But it's still very annoying to need to have this switch for every possible my_function1, my_function2, etc.
So far, the solution I've come up with is to use a functional approach and have a method that accepts a functor:
template <typename ReturnType, typename FunctorType>
ReturnType mxarr_apply(const mxArray *inarr, FunctorType functor) {
void *data = mxGetData(inarr);
switch (mxGetClassID(inarr)) {
case mxDOUBLE_CLASS:
return (ReturnType) functor((double *) data);
...
This way I can put my logic in the functor (with the operator() templated) and not have to recreate the switch over and over.
But I wonder if there is some other way? In Java I think I could just have a function that translates the mxClassID directly into a class reference that could then be used to instantiate a type flexibly at runtime, but this doesn't seem to be an option in C++.
2 comentarios
Jan
el 19 de Sept. de 2011
I agree, that this is a common problem. Both solutions are not really nice. You could use the first method and write it to a separate function, which is included at the compilation.
Respuestas (0)
Ver también
Categorías
Más información sobre Call C++ from MATLAB en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!