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
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.
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Call C from MATLAB 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!