我有一个很大的 C++ 代码,我想将其集成到 MATLAB 中,以便我可以在我的 matlab 代码中使用它。如果它是一个单一的代码,那么制作它的 mex 文件将是最好的选择。但由于现在它是一个需要编译和构建才能运行的代码,我不知道如何使用该代码中的函数。
为整个代码制作 mex 文件是唯一的选择还是还有其他解决方法?另外我想要一些关于如何为整个代码创建 mex 文件然后构建它的帮助。
为了获得更多见解,这是我尝试在 matlab 中集成的代码http://graphics.stanford.edu/projects/drf/densecrf_v_2_2.zip。谢谢!
首先,您需要编译库(静态或动态链接)。以下是我在 Windows 计算机上执行的步骤(我有 Visual Studio 2013 作为 C++ 编译器):
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
生成的分割图像:
另一种方法是将大型 C++ 代码编译成共享库(.dll 或 .so,具体取决于您的操作系统),然后使用
loadlibrary
在 Matlab 中加载该库。calllib
调用其每一个 API 函数。
示例: 假设您在 Linux 环境中工作,并且文件
myLib.cpp
中有 C++ 代码以及头文件 myLib.h
,那么您可以使用 g++
创建共享库
$ g++ -fPic -c myLib.cpp
$ g++ -shared -o myLib.so myLib.o
现在,在 Matlab 中,您可以加载库(假设 .so 文件和 .h 文件位于您的 matlab 路径中)
>> loadlibrary( 'myLib', 'myLib.h' );