I have a function that I'm writing as a MATLAB mex file. This function has to use MEX because it is interfacing with a piece of hardware in C++. There are a lot of options that can be set, and I would like to use a containers.Map
to pass them. (Otherwise, I'd need a huge number of function parameters.)
I don't see any way of accessing the Map's operator that retrieves values using keys. I tried using mexCallMATLAB
, but my various approaches failed. Is there a way to do this?
I thought maybe Map implemented this operator using subsref
, but this fails in MATLAB, so I'm guessing the equivalent in a mex file would fail, too:
dict = containers.Map('foo', 3)
subsref(dict, struct('type', '.', 'subs', 'foo'))
Upvote for @nirvana-msu for getting me on the right track. Also, thanks to @horchler for suggesting that using a struct
instead is a better idea. Here's how to access a containers.Map
in C++ after making one in MATLAB with a field named foo
:
#include <mex.h>
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
mxArray *args[2];
args[0] = const_cast<mxArray*>(prhs[0]);
const char **fields = (const char **) mxCalloc(2, sizeof(*fields));
fields[0] = "type";
fields[1] = "subs";
args[1] = mxCreateStructMatrix(1, 1, 2, fields);
auto typeStr = mxCreateString("()");
mxSetField(args[1], 0, "type", typeStr);
auto mapKey = mxCreateString("foo");
mxSetField(args[1], 0, "subs", mapKey);
mxArray *output;
mexCallMATLAB(1, &output, 2, args, "subsref");
mexPrintf("%f\n", mxGetScalar(output));
mxDestroyArray(args[1]);
mxFree(fields);
}