Byte ordering in calls from C/C++ to a Matlab-compiled DLL
Mostrar comentarios más antiguos
I am having a strange issue with passing information to and from a compiled MATLAB DLL from C/C++.
First, here is my function:
function y = foo(x)
a=0.5;
y=x.*a;
And here is how I compile it using Microsoft VS 9.0:
mcc -B csharedlib:foolib foo.m -C
And here is my C++ pseudo-code:
In header
mxArray *x_ptr, *y_ptr;
In constructor
mclInitializeApplication(NULL,0);
foolibInitialize();
In main
// note: myBuffer is a float* of length numSamples
x_ptr = mxCreateDoubleMatrix(numSamples, 1, mxREAL);
y_ptr = mxCreateDoubleMatrix(numSamples, 1, mxREAL);
memcpy(mxGetPr(x_ptr), (double*)myBuffer, numSamples*sizeof(double));
mlfFoo(1, &y_ptr, x_ptr);
memcpy(myBuffer, (float*)mxGetPr(y_ptr), numSamples*sizeof(float));
My deconstructor
foolibTerminate();
mxDestroyArray(x_ptr); x_ptr=NULL;
mxDestroy(y_ptr); y_ptr = NULL;
mclTerminateApplication();
But here is the weird part - if a (in foo.m) is 1/2 or 1/4 or 1/8, etc. then while it doesn't sound like gain is really being applied (in fact it sounds slightly distorted), at least it is passing through the input. However, if I use ANY other gain values, e.g. 0.51 instead of 0.50, the output is complete and utter garbage.
In researching this problem, I realized that the fractions listed above only alter the exponent of a float, and doing an odd fraction such as 0.51 also changes the mantissa.
So my thoughts are that there is some sort of endianness or byte-ordering problem going on?!? Does anyone have any thoughts on this?!?!?
Respuesta aceptada
Más respuestas (1)
Walter Roberson
el 20 de Jul. de 2011
1 voto
In some parts of your code you are treating myBuffer as being an array of double, and in other parts you are treating it as being an array of float. That seems to be asking for trouble. I don't know why you are thinking that your foo function will be returning a float when it does not use single() to force the computation result to single precision.
1 comentario
Oygo
el 20 de Jul. de 2011
Categorías
Más información sobre Generating Code en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!