开发者

Getting MATLAB variable (string) from C

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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜