将C ++库转换为MATLAB mex

时间:2014-09-15 09:57:12

标签: c++ matlab integration mex

我有一个很大的C ++代码,我想将它集成到MATLAB中,以便我可以在我的matlab代码中使用它。如果是单个代码使其mex文件成为最佳选择。但是从现在起它是一个需要编译和构建才能运行的代码,我不知道如何使用这段代码中的函数。
为整个代码制作mex文件是唯一的选择还是有其他解决方法吗?另外,我想要一些帮助,我如何为整个代码制作mex文件,然后构建它。

有关更深入的了解,这是我尝试在matlab http://graphics.stanford.edu/projects/drf/densecrf_v_2_2.zip中集成的代码。谢谢!

2 个答案:

答案 0 :(得分:3)

首先,您需要编译库(静态或动态链接)。以下是我在Windows机器上执行的步骤(我将Visual Studio 2013作为C ++编译器):

  • 使用CMake生成Visual Studio项目文件,如README文件中所述。
  • 启动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

生成的分段图像:

out.ppm

答案 1 :(得分:0)

另一种方法是将大型C ++代码编译为shared library(.dll或.so,具体取决于您的操作系统),然后使用loadlibrary在Matlab中加载此库。
加载库后,您可以使用calllib调用其每个API函数。


示例:假设您在Linux环境中工作,并且您在文件myLib.cpp中拥有头文件myLib.h的c ++代码,那么您可以使用{{1创建共享库

g++

现在,在Matlab中,您可以加载库(假设.so文件和.h文件在您的matlab路径中)

$ g++ -fPic -c myLib.cpp
$ g++ -shared -o myLib.so myLib.o
相关问题