无法生成 mex 文件

Unable to build mex file

本文关键字:mex 文件      更新时间:2023-10-16

我按照 MATLAB 示例从这里创建了一个mex文件 https://uk.mathworks.com/help/matlab/matlab_external/standalone-example.html

它生成的源代码如下

#include "mex.h"
/* The computational routine */
void arrayProduct(double x, double *y, double *z, mwSize n)
{
    mwSize i;
    /* multiply each element y by x */
    for (i=0; i<n; i++) {
        z[i] = x * y[i];
    }
}
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
{
    double multiplier;              /* input scalar */
    double *inMatrix;               /* 1xN input matrix */
    size_t ncols;                   /* size of matrix */
    double *outMatrix;              /* output matrix */
    /* check for proper number of arguments */
    if(nrhs!=2) {
        mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs","Two inputs required.");
    }
    if(nlhs!=1) {
        mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs","One output required.");
    }
    /* make sure the first input argument is scalar */
    if( !mxIsDouble(prhs[0]) || 
         mxIsComplex(prhs[0]) ||
         mxGetNumberOfElements(prhs[0])!=1 ) {
        mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notScalar","Input multiplier must be a scalar.");
    }
    /* make sure the second input argument is type double */
    if( !mxIsDouble(prhs[1]) || 
         mxIsComplex(prhs[1])) {
        mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notDouble","Input matrix must be type double.");
    }
    /* check that number of rows in second input argument is 1 */
    if(mxGetM(prhs[1])!=1) {
        mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notRowVector","Input must be a row vector.");
    }
    /* get the value of the scalar input  */
    multiplier = mxGetScalar(prhs[0]);
    /* create a pointer to the real data in the input matrix  */
    inMatrix = mxGetPr(prhs[1]);
    /* get dimensions of the input matrix */
    ncols = mxGetN(prhs[1]);
    /* create the output matrix */
    plhs[0] = mxCreateDoubleMatrix(1,(mwSize)ncols,mxREAL);
    /* get a pointer to the real data in the output matrix */
    outMatrix = mxGetPr(plhs[0]);
    /* call the computational routine */
    arrayProduct(multiplier,inMatrix,outMatrix,(mwSize)ncols);
}

当我运行命令mex arrayProduct.cpp(我的文件名(时,出现以下错误:

使用"Microsoft视觉C++ 2017"进行构建。 使用 mex 时出错 链接:错误LNK2001:未解析的外部符号 mexfilerequiredapiversion arrayProduct.lib : 致命错误 LNK1120: 1 个未解析的外部

我使用的是 MATLAB 2015b 32 位,带有 Visual Studio 2017 C++编译器。制作 MATLAB 教程中未提及的mex文件是否需要一些初步设置?

MATLAB R2015b 支持的最年轻的编译器是 MSVC Professional 2015。此外,R2015b 是支持 32 位的最新版本。您的编译器可能是 MSVC 2017,64 位。

尝试安装 。NET4 + SDK 7.1,在 MATLAB 中选择它,然后重新运行你的 mex 命令。这是R2015b官方支持的编译器,我希望这可以解决您的问题。

注意:对我来说,.NET4拒绝安装,因为它检测到以前安装的框架,但是这个答案为我解决了这个问题。