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.

 採用された回答

MathWorks Support Team
MathWorks Support Team 2009 年 6 月 27 日

0 投票

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 件のコメント

James Tursa
James Tursa 2017 年 3 月 17 日
編集済み: James Tursa 2017 年 3 月 17 日
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 ExchangeWrite 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