【问题标题】:not able to return QString from c++ function to PERL function by using SWIG无法使用 SWIG 将 QString 从 C++ 函数返回到 PERL 函数
【发布时间】: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)即使我没有收到任何东西。

标签: c++ qt swig perl


【解决方案1】:

如果你不能使用QString返回值,也许你可以使用std::string

如果两者都失败并且你没有限制,你可以做一些肮脏的把戏:

QString get_string()
{
  static QByteArray arr;
  QString str = getString();
  arr = str.toLocal8Bit();
  return arr.constData();
}

请注意,在您的应用运行之前,arr 变量不会被释放

编辑:找到了一个可能的解决方案,只使用std::string ... string arguments are not recognized by SWIG

【讨论】:

  • 我也面临同样的问题,即使使用 int(还有一个返回 int 的函数),我已经尝试返回常量(例如:10),即使这样我也没有收到任何东西。所以我认为问题是别的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-15
  • 1970-01-01
相关资源
最近更新 更多