我已经很久没有用C++编程了,但是我最近写了一个C++函数,遇到了一些麻烦。该函数返回一个结构 Result,其中包含一些字符串。我以为我为字符串分配了内存,但 jsonResult 有时会被部分覆盖。
//The structs
struct Interp {
int score;
char* sentence;
char* jsonResult;
};
struct Result {
int resultCode;
char* errorMessage;
Interp interp;
};
...
//Inside the function
Result result;
//Store decode
const char* jsonResult,* sentence;
if (result.resultCode == -1)
{
LVInterpretation interp = port.GetInterpretation(voiceChannel, 0);
result.interp.score = interp.Score();
sentence = interp.InputSentence();
jsonResult = interp.ResultData().Print(SI_FORMAT_ECMA);
}
//Allocate memory for strings
result.interp.jsonResult = new char[strlen(jsonResult) + 1];
strcpy(result.interp.jsonResult, jsonResult);
result.interp.sentence = new char[strlen(sentence) + 1];
strcpy(result.interp.sentence, sentence);
result.errorMessage = new char[strlen(errorMessage) + 1];
strcpy(result.errorMessage, errorMessage);
return result;
其他信息: 我正在使用 ctypes 观察我编写的 python 绑定(bind)背后的所有这些。不过,不要认为这真的会产生任何影响。
最佳答案
使用std::string
。你不会后悔的。
关于C++分配内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4139576/