返回const char*; 静态是多么丑陋?

Mik*_*ike 4 c c++ python swig

由于我无法控制的原因,我需要const char*从函数返回,但我不知道char在编译时需要什么.我的解决方案如下:

const char* __str__() {
  static std::string String;
  String = [some fancy stuff];
  return String.c_str();
}
Run Code Online (Sandbox Code Playgroud)

static防止串对退出功能的破坏,但它也意味着记忆棒周围,直到我的程序退出(右?).因为返回的字符串有时可能很大(GB),这可能是一个真正的问题.

我通常不惜一切代价避免使用指针,而且只能static用于班级成员,所以我不能100%确定我在做什么.这保证有效吗?有没有更好的办法?

[这个问题的上下文是使用该__str__方法在python中打印一个复杂的对象.我在我的c ++代码中定义了该方法,然后由SWIG包装.SWIG的例子显示了使用static,但我不清楚这是唯一的方法.我愿意接受建议.]

wal*_*lyk 10

static 除分配范围外,还会出现其他麻烦:

  • 该功能不可重入
  • 当调用者完成返回值时,无法清除

有什么理由不返回值并让调用者释放它?:

const char* __str__() {
    char *s = malloc(2 * 1024 * 1024 * 1024);  // 2 GB
    [some fancy stuff with s];
    return s;
}

...

const char *magic = __str__();
[do something with magic]
free (magic);  magic = NULL;   // all done
Run Code Online (Sandbox Code Playgroud)


Mar*_*nen 5

正如@Prætorian所说,SWIG可以将std :: string返回给Python.以下是我认为您正在研究的S​​WIG示例中的示例.还显示了一种避免在C++中使用保留名称的方法:

%module x

%{
#include "x.h"
%}

%include <windows.i>
%include <std_string.i>
%rename(__str__) display;
%include "x.h"
Run Code Online (Sandbox Code Playgroud)

XH

#include <sstream>
#include <string>

class Vector
{
public:
    double x,y,z;
    Vector(double a,double b,double c):x(a),y(b),z(c) {}
    ~Vector() {}
#ifdef SWIG
    %extend {
        std::string display()
        {
            std::ostringstream temp;
            temp << '[' << $self->x << ',' << $self->y << ',' << $self->z << ']';
            return temp.str();
        }
    }
#endif
};
Run Code Online (Sandbox Code Playgroud)

产量

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import x
>>> v = x.Vector(1.0,2.5,3.0)
>>> print v
[1,2.5,3]
Run Code Online (Sandbox Code Playgroud)