在Matlab中构建后Mex文件输出崩溃

时间:2015-12-08 22:12:55

标签: matlab

#include <stdio.h> %%Initialization
#include <math.h>
#include "mex.h" 
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{

 int first;
 int second; 
 int add,subtract,multiply
 first = (int)(mxGetPr(prhs[0])); 
 second = (int)(mxGetPr(prhs[1]));

 add= first+second;
 subtract=first-second;
 multiply=first*second;
 add=plhs[0] = mxCreateDoubleScalar(0);
 subtract=plhs[1] = mxCreateDoubleScalar(1);
 multiply=plhs[2] = mxCreateDoubleScalar(2); 
 mxDestroyArray(add)
 mxDestroyArray(subtract)
 mxDestroyArray(multiply)
 return;
 }
  

每次都崩溃。它在系统工作区中构建,但在运行(F9)

后崩溃

1 个答案:

答案 0 :(得分:1)

我不知道这段代码应该做什么,但是整个地方都有很多错误:

  1. (int)(mxGetPr(prhs[0]))我无法想到将double *投射到int有任何意义的情况。我们正在获取数组的内存地址然后可能将其截断为32位?这几乎肯定不是你想要的。
  2. subtract=plhs[1]您无法将MXArray *分配给整数。
  3. mxDestroyArray(add)你不应该在整数上调用mxDestroyArray。另外,你不应该在plhs[0]上调用它,因为Matlab会处理它。
  4. c和c ++中的指针非常棘手。要编写c或c ++代码,理解指针等......需要近乎完美。你真的需要学习如何编写基本程序,用c / c ++进行基本编码,理解类型,理解指针等......然后才能用Mex做事。

    c / c ++是很棒的语言!但我先在其他地方学习它们。为Matlab mex编写c / c ++代码对于学习c / c ++基础知识来说是一个令人困惑/特殊的环境。