How do I use the mxCreateCharArray routine in my C-Mex function?

I would like to put a two dimensional array of characters into the MATLAB environment from my C Mex-file. I would like to use the mxCreateCharArray routine to do that.

 Akzeptierte Antwort

The mxCreateCharArray routine is similar to the mxCreateNumericArray routine in the sense that they both create multidimensional arrays. The first is an array of characters and the second is different data types.
The lines of code below demonstrate an example with mxCreateCharArray:
/*Filename: TEST.C*/
#include <string.h>
#include "mex.h"
#define TOTAL_ELEMENTS 4
void
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
int bytes_to_copy;
mxChar *dataptr;
mxChar data[]={'a','b','c','d'};
int dims[] = {2, 2};
/* Check for proper number of input and output arguments */
if (nrhs > 1) {
mexErrMsgTxt("Too many input arguments.");
}
if(nlhs > 1){
mexErrMsgTxt("Too many output arguments.");
}
/* Create a 2-Dimensional string mxArray. */
plhs[0]= mxCreateCharArray(2, (const int *)dims);
/* populate the real part of the created array */
dataptr = (mxChar *)mxGetData(plhs[0]);
bytes_to_copy = TOTAL_ELEMENTS * mxGetElementSize(plhs[0]);
memcpy(dataptr,data,bytes_to_copy);
}
At the MATLAB Command prompt you will get:
>> mex test.c
>> test
ans =
ac
bd

1 Kommentar

This will fail on a 64-bit machine where mwSize is equivalent to a size_t, since an int will be 32-bits and not match. The proper way to do the dimensions is to use mwSize instead of int:
mwSize dims[] = {2, 2};
:
plhs[0]= mxCreateCharArray( 2, dims );

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Hilfe-Center und File Exchange

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by