Bwood94 Bwood94 - 1 year ago 215
C Question

Casting Issue in MATLAB C/MEX

I'm passing an array of complex doubles from matlab into a cmex file in order to perform a sequential operation on them. When I cast the number retrieved from the mxArray to a double, it seems to be misinterpreting the code.

double *Xr, *Xi;
Xr = mxGetPr(IN_0);
Xi = mxGetPi(IN_0);
for(i = 1; i < 20; i++){
printf("%d: %d+i%d\n",i,*Xr,*Xi);

This yields very high values such as the one that follows

15: -803610318+i-1940584014
16: 1832649449+i300289408
17: -1676226884+i1653608050
18: -88066604+i-2135293182

I noticed if I replace the
with a
so that printf reads it as a floating point number, the output matches my matlab variable that is being passed in

printf("%d: %f+i%f\n",i,*Xr,*Xi);


15: -0.000538+i0.000221
16: -0.000602+i0.000596
17: 0.000550+i-0.000179
18: -0.000371+i-0.001420

This is correct.

However, if I try to change the type of my pointer to float I get the incorrect answer again.

float *Xr, *Xi;
Xr = mxGetPr(IN_0);
Xi = mxGetPi(IN_0);
for(i = 1; i < 20; i++){
printf("%d: %f+i%f\n",i,*Xr,*Xi);


15: 4596027085627908600000000000000.000000+i-0.000000
16: -0.392485+i0.362957
17: -82893360.000000+i0.000000
18: 0.412054+i-0.383178

To me it looks as if the data is coming through encoded in a floating point representation, but is seen by the compiler as a double, causing it to be casted to float when assigned to a float type. Other than that I do not know how to solve this problem and help would be appreciated.

Answer Source

Using a %d specifier with anything other than an int argument (or something that promotes to int) is undefined behavior.

For your third example, casting pointers does not convert the underlying data. You are assigning a pointer to double to a pointer to float, and dereferencing that is undefined behavior.

The data coming from Matlab is an array of doubles and must be treated that way. If you need to, you can convert the elements one at a time to another type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download