簡體   English   中英

將C ++庫轉換為MATLAB mex

[英]Converting a C++ library into MATLAB mex

我有一個很大的C ++代碼,我想將其集成到MATLAB中,以便可以在我的matlab代碼中使用它。 如果是單個代碼,則使其mex文件成為最佳選擇。 但是由於現在它是一個需要編譯和構建才能運行的代碼,所以我不知道如何使用此代碼中的函數。
使整個文件的mex文件成為唯一選擇還是有其他解決方法? 另外,我想對如何制作整個代碼的mex文件然后進行構建提供一些幫助。

為了獲得更多的見解,這是我嘗試在matlab中集成的代碼http://graphics.stanford.edu/projects/drf/densecrf_v_2_2.zip 謝謝!

首先,您需要編譯庫(靜態或動態鏈接)。 這是我在Windows機器上執行的步驟(我將Visual Studio 2013作為C ++編譯器):

  • 如自述文件中所述,使用CMake生成Visual Studio項目文件。
  • 啟動VS,並編譯densecrf.sln解決方案文件。 這將產生一個靜態庫densecrf.lib

接下來,修改示例文件dense_inference.cpp以使其具有MEX功能。 我們將main功能替換為:

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

而不是從argc / argv中接收參數,我們將從輸入mxArray獲得參數。 所以像這樣:

if (nrhs<3 || nlhs>0)
    mexErrMsgIdAndTxt("mex:error", "Wrong number of arguments");

if (!mxIsChar(prhs[0]) || !mxIsChar(prhs[1]) || !mxIsChar(prhs[2]))
    mexErrMsgIdAndTxt("mex:error", "Expects string arguments");

char *filename = mxArrayToString(prhs[0]);
unsigned char * im = readPPM(filename, W, H );
mxFree(filename);

//... same for the other input arguments
// The example receives three arguments: input image, annotation image,
// and output image, all specified as image file names.

// also replace all error message and "return" exit points
// by using "mexErrMsgIdAndTxt" to indicate an error

最后,我們編譯修改后的MEX文件(將編譯后的LIB放在同一example文件夾中):

>> mex -largeArrayDims dense_inference.cpp util.cpp -I. -I../include densecrf.lib

現在我們從MATLAB內部調用MEX函數:

>> dense_inference im1.ppm anno1.ppm out.ppm

產生的分割圖像:

ppm

一種替代方法是將大型C ++代碼編譯為共享庫 (.dll或.so,具體取決於您的操作系統),然后使用loadlibrary將其加載到Matlab中。
加載庫后,您可以使用calllib調用其每個API函數。


示例:假設您在Linux環境中工作,並且在文件myLib.cpp具有頭文件myLib.h c ++代碼,則可以使用g++創建共享庫

$ g++ -fPic -c myLib.cpp
$ g++ -shared -o myLib.so myLib.o

現在,在Matlab中,您可以加載該庫(假設.so文件和.h文件位於您的matlab路徑中)

>> loadlibrary( 'myLib', 'myLib.h' );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM