关于matlab:在mex文件中,我无法通过matlab2016a中的指针覆盖标量,尽管我可以覆盖2013a中的标量以及2016a中的数组

In mex file, I can't overwrite scalar through the pointer in matlab2016a, although I can overwrite the scalar in 2013a and also the array in 2016a

[环境]

OS:OSX10.11和maxOS Sierra(10.12)

MATLAB:matlab2013a和matlab2016a

Xcode:xcode7和xcode8

在工作中,我必须在旧程序包中使用以下mex文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//destructiveMatrixWriteAtIndices.c
//------------------------------------------------------
#include <matrix.h>  /* Matlab matrices */
#include <mex.h>
#include <stddef.h>  /* NULL */
#define notDblMtx(it) (!mxIsNumeric(it) || !mxIsDouble(it) || mxIsSparse(it) || mxIsComplex(it))
void mexFunction(int nlhs,       /* Num return vals on lhs */
                 mxArray *plhs[],    /* Matrices on lhs      */
                 int nrhs,       /* Num args on rhs    */
                 const mxArray *prhs[]     /* Matrices on rhs */
                )
{
 double *mtx;
 double *newValues;
 double *doubleStartIndex;
 int i, startIndex, size;
 mxArray *arg;

 if (nrhs != 3) mexErrMsgTxt("requires 3 arguments.");

 /* ARG 1: MATRIX  */
 arg = prhs[0];
 if notDblMtx(arg) mexErrMsgTxt("MTX arg must be a real non-sparse matrix.");
 mtx = mxGetPr(arg);

 arg = prhs[1];
 if notDblMtx(arg) mexErrMsgTxt("MTX arg must be a real non-sparse matrix.");
 newValues = mxGetPr(arg);
 size = (int) mxGetM(arg) * mxGetN(arg);

 arg = prhs[2];
 if notDblMtx(arg) mexErrMsgTxt("MTX arg must be a real non-sparse matrix.");
 doubleStartIndex = mxGetPr(arg);
 startIndex = (int) doubleStartIndex[0];

 for (i=0; i<size; i++){  
     mtx[i+startIndex] = newValues[i];        
 }
 return;
}
//------------------------------------------------------

此mex文件是通过指针覆盖标量和矩阵部分的功能。

例如在matlab2013a命令窗口中(matlab2013a中的标量)

1
2
a = 1;
destructiveMatrixWriteAtIndices(a, 3, 0);

,变量" a"变为" 3"。

例如在matlab2013a和matlab2016a命令窗口中(matlab2013a和matlab2016a中的矩阵)

1
2
a = [1, 2];
destructiveMatrixWriteAtIndices(a, 3, 0);

,变量" a"变为" [3,2]"。

例如在matlab2016a命令窗口中(在matlab2016a中为标量)

1
2
a = 1;
destructiveMatrixWriteAtIndices(a, 3, 0);

,变量" a"变为" 1"!为什么?

我还使用了lldb,并揭示了此代码的奇怪行为。

在matlab2013a和matlab2016a中,当我运行以下代码段时。

1
2
a = 1;
destructiveMatrixWriteAtIndices(a, 3, 0);

在两个matlab的llx函数的末尾lldb都显示" * mtx = 3",但是mex函数无法通过指针传递结果(* mtx = 3或prhs [0] = 3)在唯一的matlab2016a中。

这是非常奇怪的行为!

※我知道此mex函数非常危险,但是在我必须使用的package中的某些地方使用了此mex函数。因此,我必须修复此mex文件,并使程序包在matlab2016a中运行。

请帮助我。


我很确定您不打算在mex函数中修改输入数组。 Matlab是否曾经复制过传递给mex函数的数据? " matlab "解决方案可能是将修改后的数组作为mex的输出返回,而不是就地进行修改。