Using structures in MEX files
Show older comments
I'm learning how to use MEX files and I have a problem with using structures. I'm trying to convert to C a Matlab function that has a header like this:
writer = writeBit( writer, bit )
writer is a structure with four fields: buffer (1x1024 array interpreted as bytes), position (scalar), mask (scalar) and fileName (string).
I've created a mex file that looks like this:
#include <mex.h>
#include <string.h>
#include "writeBitC.h"
void mexFunction( int nlhs, mxArray *plhs[ ], int nrhs, const mxArray *prhs[ ] ) {
/*checking input & output params here*/
const char *fieldNames[] = {"buffer", "position", "mask", "fileName" };
mxArray* bufferArray = mxGetField( prhs[ 0 ],
0, fieldNames[ 0 ] );
mxArray* positionArray = mxGetField( prhs[ 0 ],
0, fieldNames[ 1 ] );
mxArray* maskArray = mxGetField( prhs[ 0 ],
0, fieldNames[ 2 ] );
mxArray* fileNameArray = mxGetField( prhs[ 0 ],
0, fieldNames[ 3 ] );
int bit = mxGetScalar( prhs[ 1 ] );
writer.position = ( (unsigned int) mxGetScalar(
positionArray ) ) - 1;
writer.mask = (char) mxGetScalar(
maskArray );
writer.fileName = (char*) mxGetChars( fileNameArray );
char* bufferDataPointer = (char*) mxGetChars(
bufferArray );
memcpy( writer.buffer, bufferDataPointer, BUFFER_SIZE );
writeBitC( bit );
memcpy( bufferDataPointer, writer.buffer, BUFFER_SIZE );
int dims[ 1 ] = { 1 };
plhs[ 0 ] = mxCreateStructArray( 1, dims, 4, fieldNames );
mxSetField( plhs[ 0 ], 0, fieldNames[ 0 ],
bufferArray );
mxSetField( plhs[ 0 ], 0, fieldNames[ 1 ],
mxCreateDoubleScalar( writer.position + 1 ) );
mxSetField( plhs[ 0 ], 0, fieldNames[ 2 ],
mxCreateDoubleScalar( writer.mask ) );
mxSetField( plhs[ 0 ], 0, fieldNames[ 3 ],
fileNameArray );
}
writeBitC is the function that performs all the operations on the structure. The writer structure is defined like this:
struct __writer {
char buffer[ BUFFER_SIZE ];
unsigned int position;
char mask;
char* fileName;
} writer;
writer is a global variable, so it's not passed to the writeBitC function as parameter. This code compiles but causes Matlab to freeze. I suspect that I did something wrong with the char arrays and memcpy function, but I can't track the bug :/ I would greatly appreciate some guidance.
Jan
Accepted Answer
More Answers (0)
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!