[英]How can I use Matlab engine in a mex function called from Matlab
我想制作一個可以從Matlab調用的mex程序,用戶可以在其中注冊要用於處理的Matlab函數。 然后,程序將使用此功能在后台處理來自另一個程序的數據。 mex程序與外部程序之間的通信是通過共享的全局緩沖區進行的,我通過互斥鎖來跟蹤該緩沖區。 該部分實際上似乎起作用。 問題是Matlab是單線程的,我想在后台處理數據,以便用戶可以繼續使用Matlab。 由於Matlab是單線程的,所以我的解決方案是創建一個新線程並從中啟動Matlab引擎。 為此,我需要從Matlab調用的mex文件中調用Matlab引擎。 當我嘗試執行此操作時,程序會生成正常,但是當我嘗試打開新引擎時,Matlab崩潰。 使用下面的測試示例,如果我使用test('process2')
調用程序(從Matlab內部),則Matlab停滯,並且當我使用ctrl-c時Matlab崩潰。 使用test('process')
有時似乎可以工作,但可能會使Matlab在十個調用之一中崩潰。
#include "mex.h"
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <stdlib.h>
#include <matrix.h>
#include <unistd.h>
#include "engine.h"
void* local_process(void *arg) {
Engine *engine;
engine = engOpen(NULL);
engClose(engine);
}
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
if ( (nrhs<1) || (! mxIsChar(prhs[0])) ) {
mexErrMsgTxt("First argument should be a command (string)");
return;
}
/* Read command string */
int buflen = mxGetNumberOfElements(prhs[0])+1;
char* buf = mxCalloc(buflen, sizeof(char));
if (mxGetString(prhs[0], buf, buflen) != 0)
mexErrMsgTxt("Could not read command string");
mexPrintf("Command: %s\n",buf);
if (strcmp(buf,"process")==0) {
pthread_t thread;
pthread_create(&thread,NULL,local_process,NULL);
}
else if (strcmp(buf,"process2")==0) {
Engine *engine;
engine = engOpen(NULL);
engClose(engine);
}
}
如果仍然值得關注,我編譯了沒有線程部分(只有“ process2”的情況)的代碼,沒有錯誤,沒有停頓,沒有問題。 即
#include <mex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <matrix.h>
#include <engine.h>
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
if ( (nrhs<1) || (! mxIsChar(prhs[0])) )
{
mexErrMsgTxt("First argument should be a command (string)");
return;
}
/* Read command string */
int buflen = mxGetNumberOfElements(prhs[0])+1;
char* buf = (char*)mxCalloc(buflen, sizeof(char));
if (mxGetString(prhs[0], buf, buflen) != 0)
mexErrMsgTxt("Could not read command string");
mexPrintf("Command: %s\n",buf);
Engine *engine;
engine = engOpen(NULL);
engClose(engine);
}
跑得好 我在裝有Visual Studio 2010的Windows計算機上。
然而,顯然有通過mex處理Matlab引擎的特性。 在此鏈接上,您可以找到我最近遇到的類似情況以及解決方法: http : //www.mathworks.com/matlabcentral/newsreader/view_thread/327157#898916
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.