Matlab C++ - Receive Dynamic Size Output type (emx

2019-08-09 07:51发布

问题:

I have converted some matlab code to C++ using coder.

void myfunction(const emxArray_real_T *input, emxArray_real_T *output){ ... }

I have setup to send emxArray_real_T type inputs without any issues. How do I setup to receive dynamic sized output in C++ which is calling myfunction?

Code updated:

main(){ 
. 
. 
. 
double *inputVec; 
inputVec=(double*)malloc(1000 * sizeof(double)); 
emxArray_real_T *input;
emxArray_real_T *output;

input=emxCreateWrapper_real_T(&inputVec[0],1,1000); 
output = emxCreateWrapper_real_T(NULL,0,0);

myfunction(input,output); 

emxDestroyArray_real_T(input);
emxDestroyArray_real_T(output);
.
.
}

This compiles just fine but errors out saying *** glibc detected *** /data/myscript : double free or corruption (!prev): 0x000000000de54920 ***

回答1:

You may check https://stackoverflow.com/a/24271438/3297440 which seems to cover a similar issue.

In this particular case, the issue is likely that the memory pointed to by output was never initialized. You can use one of the emxCreate* functions in myfunction_emxAPI.h to initialize an empty emxArray and pass that in. The choice between emxCreateWrapper_real_T and emxCreate_real_T relies on whether or not you want to own the memory allocated for the data. The former puts the ownership in your hands and the latter is used when the emxArray owns the memory.

Something like:

output = emxCreateWrapper_real_T(NULL,0,0);

before the call to myfunction should do the trick.

By the way, don't forget to call:

emxDestroyArray_real_T(input);
emxDestroyArray_real_T(output);

at the end to clean up any memory allocated inside of the emxArrays. Even if the wrapper functions are used, storage for the size vectors may be allocated.