How to decode mxGetData void pointer nicely

5 次查看(过去 30 天)
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 个评论
Jan
Jan 2011-9-19
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 2011-9-20
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.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Call C from MATLAB 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by