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.

 채택된 답변

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

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 );

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by