2014-07-23 324 views
-2

我编写了一个C++函数及其关联的mex。但是C++函数的一种输入是double *错误无法从'void *'转换为'float *'

  1. 函数pointwise_search的输出是一个指针。我被告知我应该删除它。但我不知道我应该删除它,因为我需要它作为输出。

  2. 从答案中,我知道我应该检查mxIsSingle的输入类型。所以我纠正了功能mexFunction。但是有一个错误error C2440: '=' : cannot convert from 'void *' to 'float *'

  3. 在Matlab中,我应该叫喜欢pointwise_search(浮动* P ,浮动q , num_thres,浮动ñ, len)。如果我在matlab中有矢量v_in_matlab = rand(5,1)。我我应该得到它的p=single(v_in_matlab);指针,提前然后pointwise_search(p...

感谢。

#include "mex.h" 
#include <iostream> 
#include <algorithm> 
#include <functional> 
#include <vector> 

using namespace std; 


float * pointwise_search(float *p,float *q,int num_thres, float* n, int len) 
{ 
    vector<float> P(p, p + num_thres); 
    vector<float> Q(q, q + num_thres); 
    int size_of_threshold = P.size(); 
    float *Y=new float[len]; 
    float *z=new float[len]; 
    typedef vector<float > ::iterator IntVectorIt ; 
    IntVectorIt start, end, it, location ; 
    start = P.begin() ; // location of first 
    // element of Numbers 

    end = P.end() ;  // one past the location 
    // last element of Numbers 

    for (int i=0;i<len;i++) 
    { 
     location=lower_bound(start, end, n[i]) ; 
     z[i]=location - start; 
     if(z[i]>0&&z[i]<size_of_threshold) 
     { 

      Y[i]=(n[i]-P[z[i]])/(P[z[i]-1]-P[z[i]])*(Q[z[i]-1]-Q[z[i]])+Q[z[i]]; 
     } 
     else 
     { 
      Y[i]=Q[z[i]]; 
     } 
    } 

    return (&Y[0]); 
} 




void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) 
    { 
    float * Numbers, *Q; 
    if (nrhs != 5) 
    { 
     mexErrMsgTxt("Input is wrong!"); 
    } 
    float *n = (float*) mxGetData(prhs[3]); 
    int len = (int) mxGetScalar(prhs[4]); 
    int num_thres = (int) mxGetScalar(prhs[2]); 

    /* Input gs */ 

    if(mxIsComplex(prhs[0]) 
    ||!mxIsSingle(prhs[0])) 
     mexErrMsgTxt("Input 0 should be a class Single"); 
    /* get the pointer to gs */ 
    Numbers=mxGetData(prhs[0]); 


    if(mxIsComplex(prhs[0]) 
    ||!mxIsSingle(prhs[0])) 
     mexErrMsgTxt("Input 0 should be a class Single"); 
    /* get the pointer to gs */ 
    Q=mxGetData(prhs[1]); 

//  float * Numbers= (float *)mxGetData(prhs[0]); 
//  float * Q= (float *)mxGetData(prhs[1]); 

    float * out= pointwise_search(Numbers,Q,num_thres,n,len); 
    //float* resizedDims = (float*)mxGetPr(out); 
} 

回答

1

在Matlab中使用single()在调用mexFunction之前转换数据。在C++端,通过mxIsSingle()验证该类型确实是单一的。在此之后,您可以愉快地投掷到float*

1

在担心MEX代码之前,先看看你的C++函数。你有一些非常明显的memory leaksnew但不是delete[])。

关于MEX你不应该看到这一点:

(float *)mxGetPr(prhs[0]) 

你不能投了double*float*,并期望号码任何意义。输入single从MATLAB和使用:

(float *)mxGetData(prhs[0]) 

,做作为Trilarion为预期的数据类型显示和测试所有的输入mxArray秒。

+0

感谢您的评论。你能告诉我应该在哪里删除函数'pointwise_search'的输出'Y' – Vivian

相关问题