Using boost in MATLAB MEX library, different from MATLAB's version

[亡魂溺海] 提交于 2019-12-02 23:46:02

One solution is to change the way matlab opens your plugin, by writing a small loader mex file which itself has no dependency on boost, call it foo.mexglx

It's mexFunction call simply does this

void mexFunction (int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[])
{
  gMexEntry (nlhs, plhs, nrhs, prhs);
}

where the gMexEntry variable is a function pointer declared as

typedef void (*entryfunc_t)(int, mxArray**, int, const mxArray**);
entryfunc_t gMexEntry;

and populated by a static constructor when the module is loaded (all error checking ignored for brevity).

fh = dlopen ('bar.mexglx', RTLD_NOW | RTLD_DEEPBIND );
void * p = dlsym (fh, "mexFunction");
gMexEntry = reinterpret_cast<entryfunc_t> (p);

The chain of events is that when Matlab calls your function, the thin wrapper with no boost dependency will open your function with the boost dependency using the RTLD_DEEPBIND option of dlopen, which will place the lookup scope of the symbols in this library (using your version of boost) ahead of the global scope (using Matlab's old boost). Then the actual mexFunction call will forward to bar.

If you do your cmdline linking correctly, using 'ldd' you should see that 'foo.mexglx' has no dependency on boost, and 'bar.mexglx' has all your usual dependencies.

I've been using this technique heavily for months with no obvious signs of failure. I do still have some slight concerns that something I don't understand might go wrong, but for the time being this is the only solution I've got (other than writing a full out-of-process execution engine replicating the mxArray interface and communicating with pipes, or linking everything statically which isn't practical for my situation)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!