我正在尝试使用mex来从Matlab调用c函数。
似乎我可以获得正确的输入,甚至计算也是正确的。但是,它返回了错误的输入。不知怎的,我搞砸输出指针请帮助。
Matlab代码:
cd /home/dkumar/MatlabCodes_DKU;
smA_System = ConstructSystemMatrix();
Dir2 = '/home/dkumar/Mex_Codes_DKU/MexCode_Working/Mex_C_Codes_DKU_makefile_Working';
% MEX
cd(Dir2);
system('make');
tic
y = normpdfDKU(1/2,0,1)
toc
C-代码
#include "mex.h"
#include <math.h>
#include <stdio.h>
/* using namespace std; */
#define pi (3.141592653589793)
extern void _main();
const int numInputArgs = 3;
const int numOutputArgs = 1;
// Function declarations.
// -----------------------------------------------------------------
double getMatlabScalar (const mxArray* ptr);
//double& createMatlabScalar (mxArray*& ptr);
// Function definitions.
// -----------------------------------------------------------------
void mexFunction (int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
int res = TestingLibraries() ;
//declare variables
mxArray *c_out_m;
double *c, p, c1;
#define B_OUT plhs[0]
// Check to see if we have the correct number of input and output
// arguments.
if (nrhs != numInputArgs)
mexErrMsgTxt(" DKU-1: Incorrect number of input arguments");
if (nlhs != numOutputArgs)
mexErrMsgTxt("DKU-2: Incorrect number of output arguments");
// Get the inputs.
double x = getMatlabScalar(prhs[0]);
double mu = getMatlabScalar(prhs[1]);
double v = getMatlabScalar(prhs[2]);
// Create the output. It is also a double-precision scalar.
//double& p = createMatlabScalar(plhs[0]);
//associate outputs
plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
//associate pointers
c = mxGetPr(plhs[0]);
// Compute the value of the univariate Normal at x.
p = (double)(exp(-(x-mu)*(x-mu)/(2*v)) / sqrt(2*pi*v));
printf("First normal value: %f\n", p);
c = &p;
}
double getMatlabScalar (const mxArray* ptr) {
// Make sure the input argument is a scalar in double-precision.
if (!mxIsDouble(ptr) || mxGetNumberOfElements(ptr) != 1)
mexErrMsgTxt("The input argument must be a double-precision scalar");
return *mxGetPr(ptr);
}
输出:
First normal value: 0.352065
y =
0
Elapsed time is 0.002202 seconds.
答案 0 :(得分:2)
问题出在这里
c = &p;
您重新定位指针c
,使其现在指向p
的地址。
您要做的是将p
的内容复制到c
当前指向的地址(您之前创建的标量的真实部分)。
*c = p;