【发布时间】:2015-04-07 11:51:17
【问题描述】:
我有 c++ 代码(也包括 Qt),我想使用 Perl 调用这些函数。 我们可以通过使用 SWIG 来做到这一点,所以我已经实现了接口,并做了所有需要在 Perl 脚本中使用它们的东西。
我在 c++ 中有一个函数,它返回一个 QString 值,
QString get_string()
{
return QString("mystring");
}
我又写了一个类,它将在 perl 脚本中使用,我有一个函数调用这个 get_string() 函数并返回 const char*。
const char* get_const_string()
{
QString str = get_string();
**//here I print str and str .toLocal8Bit().constData()
//both are printing the text which i shoud get here**
return str.toLocal8Bit().constData();
//here I have tried diff combinations also, as
// return str.toStdString().c_str();
}
问题是,在 get_const_string() 函数中,我可以得到我想要的字符串,但是当我在我的 perl 脚本中调用这个函数时,我得到未定义的值,即 null string
。
任何想法,这里有什么问题??
我正在使用 perl5、Qt4.8.4
提前致谢。
【问题讨论】:
-
也许问题是
get_const_string()函数中的str变量是本地的,一旦程序超出范围就销毁?结果,函数返回的char指针指向了无效的内存? -
@vahancho 所说的绝对正确,但我还要指出,即使
str不是本地的,toLocal8bit ()返回的对象也是临时的,因此无法使用在 return 语句中(constData ()只是返回其内部) -
@vahancho 和 Predelnik:那么你们有什么建议,有什么办法吗??
-
我也面临同样的问题,即使使用 int (还有一个返回 int 的函数),我已经尝试通过返回常量(例如:10)即使我没有收到任何东西。