【发布时间】:2014-06-13 06:19:35
【问题描述】:
我正在尝试构建一个 C/C++ 函数供 MATLAB 调用。这是我的 C/C++ 代码:
#include "mex.h"
double* MyarrayProduct(double* a, double* b, int N)
{
double* c = (double*)malloc(N*sizeof(double));
double* pc = c;
for (int n = 0; n < N; n++)
{
*pc = *a**b;
pc++;
a++;
b++;
}
return c;
}
/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
//------------------------------------------ Verify MEX-File Input and Output Parameters -----------------------------------------------------//
//To check for two input arguments, multiplier and inMatrix, use this code.
if(nrhs!=2)
{
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs",
"Two inputs required.");
}
//Use this code to check for one output argument, the product outMatrix.
if(nlhs!=1)
{
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs",
"One output required.");
}
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.");
}
//------------------------------------------ variable declarations here ----------------------------------------//
double *inMatrixA; /* input scalar */
double *inMatrixB; /* 1xN input matrix */
int ncols; /* size of matrix */
double *outMatrix; /* output matrix */
//------------------------------------------- read in data -----------------------------------------//
/* get the value of the scalar input */
inMatrixA = mxGetPr(prhs[0]);
/* create a pointer to the real data in the input matrix */
inMatrixB = mxGetPr(prhs[1]);
/* get dimensions of the input matrix */
ncols = mxGetN(prhs[1]);
//------------------------------------------- Prepare Output Data -----------------------------------------//
/* create the output matrix */
plhs[0] = mxCreateDoubleMatrix(1,ncols,mxREAL);
/* get a pointer to the real data in the output matrix */
outMatrix = mxGetPr(plhs[0]);
/* call the computational routine */
outMatrix = MyarrayProduct(inMatrixA,inMatrixB,ncols);
/* code here */
}
这是我的 MATLAB 结果。
>> a =[1 2 3]
a =
1 2 3
>> b = [4 5 6]
b =
4 5 6
>> mex MyarrayProduct.cpp
>> c = MyarrayProduct(a,b)
c =
0 0 0
我进入了我的 C/C++ 代码,并在
找到outMatrix = MyarrayProduct(inMatrixA,inMatrixB,ncols);
outMatrix 实际上是 4、10、18,这是正确的。但它似乎很难将结果发回。我想知道这里有什么问题?我无法在 mex 中返回指针?
【问题讨论】: