开发者

Getting MATLAB variable (string) from C

开发者 https://www.devze.com 2022-12-27 23:52 出处:网络
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 开发者_运维技巧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

精彩评论

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

关注公众号