0

I'm writing a small C application that launchs a Matlab script (.m file). I need to exchange some variables and I don't know how to get an array of chars that exists in Matlab.

I'm doing something like this:

enter code here
result = engGetVariable(ep,"X");
if (!result)
    {
    printf ("Error...");
            exit -1;
    }

int n = mxGetN(result);

    char *varx = NULL;
    memcpy(varx, mxGetData(result),n*sizeof(char));

It doesn't work. Does someone know how to get a Matlab string in C? I've read Matlab documentation about engGetVariable() and the provided example but any of this things clarify me.

Jav_Rock
  • 22,059
  • 20
  • 123
  • 164
Hamming
  • 193
  • 1
  • 1
  • 4

1 Answers1

3

Your problem is that you're trying to memcpy into memory that you never allocated. char *varx = malloc (sizeof(char) *bytes_you_need); before you do that. Setting char * to NULL means it has no memory address, and thus cannot serve as a reference to any memory.... set it to the return value of malloc, where malloc has set aside some bytes for your data.

char *varx = malloc (sizeof(char) * n);
memcpy(varx, mxGetData(result),n*sizeof(char));
printf ("%s\n", varx);
free(varx);
  • Ok, this is a problem (let me say a "lack of coffee" ;-)) But, declaring varx like you said or "char varx[1000]" there are still problems. I have been debugging and I found that if I have a variable in Matlab like "X='Hello folks!' when retriving it in C I have this: varx[0]='H' varx[1]='\0' varx[2]='e' varx[3]='\0'.. and so on. Maybe it's because in Matlab characters have 16 bits... and I'm working with 8bits. Doing in Matlab "X=int8('Hello folks!') seems to work but fails with some characters. Thanks!! – Hamming Apr 22 '10 at 13:16
  • yep, you nailed it. it's giving you back utf8, since you're getting ascii the first 8 bits will be the same, so skipping every other char will work. you might also try using wchar_t and doing it the wide character way, but it might not be necessary for your purposes. (wchar_t == char * 2) –  Apr 22 '10 at 13:28
  • I'm doing the conversion in Matlab (that it's easyer :-) to uint8 and works like a charm! – Hamming Apr 22 '10 at 13:30