【问题标题】:How MATLAB mex files access MATLAB instances?MATLAB mex 文件如何访问 MATLAB 实例?
【发布时间】:2015-12-30 06:59:40
【问题描述】:

这是每个 mex 文件的入口点:

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);

实际上mex文件是以mexFunction为主要功能的windows dll文件。 我的问题是当调用 mex 函数时,它如何从 mex 内部访问 matlab 实例特定数据。例如,考虑“mexPutVariable”函数。它的工作是“将一个数组从 MEX 函数内部复制到指定的工作区(mex 外部)”。但它如何知道“工作区”在哪里。没有参数传递给 mex(如指针),包含 matlab 实例数据(调用者)。 mex 文件只知道 nlhs、plhs、nrhs、prhs,它们都不能帮助 mex 文件挖掘 matlab 实例特定数据(调用者函数信息)。

【问题讨论】:

    标签: matlab dll mex


    【解决方案1】:

    一个可能的解决方案是"Matlab.exe"mexPutVariable 声明为导出函数:

    [Matlab.exe]
    
    int __declspec(dllexport) mexPutVariable(const char* workspace, const char* name, const mxArray* parray)
    {
        ...
    }
    

    然后很容易使用GetModuleHandleGetProcAddress 从 dll 中检索此函数:

    [Module.dll]
    
    // Declare function pointer 
    int (*FctnPtr)(const char* workspace, const char* name, const mxArray* parray);
    
    // Retreive the main executable 
    HANDLE hExe = GetModuleHandle(NULL);
    
    // Link to exported function in the exe just like you would do for any dll    
    FctnPtr mexPutVariable = (FctnPtr)GetProcAddress(hExe, "mexPutVariable");
    
    // Use exported function from the dll
    mexPutVariable("Base", "foo", myArray);
    

    为了编译 mex 文件并查看 mex.h 文件后,mexPutVariable 被声明为要链接的外部函数:

    LIBMWMEX_API_EXTERN_C int mexPutVariable(const char* workspace, const char* name, const mxArray* parray);
    

    转为简单(当编译为dll端时):

     extern "C" int mexPutVariable(const char* workspace, const char* name, const mxArray* parray);
    

    【讨论】:

    • 是可能的答案还是真实的答案?
    • 我没有 matlab 的源代码,所以它只能是一个猜测......无论如何,如果没有将指针传递给 dll,我看不到任何其他合理的回调到主进程的解决方案.
    • 作为替代方案,也许在您的 mex 源文件链接的“.lib”中,有一个导出函数 matlab 也在调用以初始化 mexPutVariable 等(即在初始化时间)。
    • 我认为这不会改变这种情况。你说的对。我认为唯一可能的答案是您在回答中提到的内容。在“.lib”中有对其他 dll 的引用。我认为在那个 dll 中执行了您提到的策略。
    • 但是如果我可以决定这样做的方法,我会添加一个名为 handle 的参数来传递 MATLAB 特定的实例数据。比如:void mexFunction(int handle,int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);然后为每个使用 MATLAB 工作区的函数添加一个句柄,例如: mexPutVariable(int handle,...); [handle是matlab实例数据结构的地址]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    相关资源
    最近更新 更多