How to decode mxGetData void pointer nicely

1 view (last 30 days)
Peter Li
Peter Li on 19 Sep 2011
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 Comments
Jan
Jan on 19 Sep 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.
Peter Li
Peter Li on 20 Sep 2011
Thanks. With the first method it seems I will always have the problem that I need to write a different switch for every possible my_function1, my_function2.
In my opinion the second method is much nicer, as it is now possible to put the mxarr_apply function in a header file and use it all the time and never have to write the switch again. It just requires writing the logic as a functor, which is not so onerous. The main problem with this approach is that it is still clumsy to get return values, so I find it is best to use this when you have only side-effects. Of course, you can assign returns by side-effect and it works okay this way, although this is a little ugly.

Sign in to comment.

Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!