I see the following issues:
1) You don't check your inputs before you use them. I would recommend putting in code to check that nrhs == 2, that prhs[0] is a structure, that prhs[0] has at least one element, that prhs[0] has the expected field names (i.e., that the results of your mxGetField calls are not NULL), that prhs[1] is a numeric scalar variable.
2) You use the result of a mxGetChars call, which returns type (mxChar * ), cast it to a (char * ) type, and then downstream attempt to use these pointers to access the data as char data. This will not work. The mxChar type is typcially a 2-byte per character type (MATLAB stores character data as 2-bytes each) whereas a char in C/C++ is 1-byte. You need to use mxArrayToString instead and convert the mxArray to a C-style character string, then use that for your downstream string processing in C, then use mxFree on that pointer to free the dynamically allocated C-style string you just created with mxArrayToString.
3) You cannot get a pointer from a field of an input mxArray (e.g., bufferArray) and simply attach it to a field of an output mxArray (i.e. plhs[0]) as you are doing. The MATLAB memory manager will likely get confused and crash later on since you have probably not told it everything it needs to know about how many copies of the data are around in memory. What you will probably need to do is either duplicate bufferArray with mxDuplicateArray and then attach that to the plhs[0] field, or use the undocumented function mxCreateSharedDataCopy to create a shared data copy of bufferArray and then attach that to the plhs[0] field.
4) You use BUFFER_SIZE for your copying, but you don't check to see that the inputs have at least that many characters to copy. Also, this won't copy a null character at the end since MATLAB strings do not terminate with null characters. Another reason to use the mxArrayToString function.
5) You are writing into bufferDataPointer, which is a data area of an input mxArray prhs[0]. This data memory can be shared at the MATLAB level with other variables, so changing it directly like you are doing has the potential unwanted side-effect of changing other MATLAB variables at the same time. This is generally not a good programming practice and can lead to strange downstream errors at the MATLAB level.
Best Answer