简体   繁体   English

从C获取MATLAB变量(字符串)

[英]Getting MATLAB variable (string) from C

I'm writing a small C application that launchs a Matlab script (.m file). 我正在编写一个启动Matlab脚本(.m文件)的小型C应用程序。 I need to exchange some variables and I don't know how to get an array of chars that exists in Matlab. 我需要交换一些变量,但我不知道如何获取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? 有人知道如何在C中获取Matlab字符串吗? I've read Matlab documentation about engGetVariable() and the provided example but any of this things clarify me. 我已经阅读了有关engGetVariable()和提供的示例的Matlab文档,但是所有这些都使我明白了。

Your problem is that you're trying to memcpy into memory that you never allocated. 您的问题是您试图将内存分配到从未分配过的内存中。 char *varx = malloc (sizeof(char) *bytes_you_need); 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 *设置为NULL意味着它没有内存地址,因此不能用作对任何内存的引用。...将其设置为malloc的返回值,其中malloc已为数据预留了一些字节。

char *varx = malloc (sizeof(char) * n);
memcpy(varx, mxGetData(result),n*sizeof(char));
printf ("%s\n", varx);
free(varx);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM