如何使用SWIG为C++类提供Python __repr __()

Don*_*eld 8 c++ python swig repr

我观察到一种类型

help
Run Code Online (Sandbox Code Playgroud)

在Python repl中,有人得到

Type help() for interactive help, ...
Run Code Online (Sandbox Code Playgroud)

当一种类型

help()
Run Code Online (Sandbox Code Playgroud)

一个人被踢进了帮助模式.我很确定这是因为site._Helper定义__repr__()(对于第一个示例)和__call__() (对于第二个示例).

我喜欢这种行为(只提示对象和可调用语法),我想对我通过SWIG导出到Python的C++类做同样的事情.这是我尝试做的一个简单例子

helpMimic.h
-----------
class HelpMimic
{
public:
    HelpMimic() {};
    ~HelpMimic() {};

    char *__repr__();
    void operator()(const char *func=NULL);
};

helpMimic.cxx
-------------
char *HelpMimic::__repr__()
{
    return "Online help facilities are not yet implemented.";
}

void HelpMimic::operator()(const char *func)
{
    log4cxx::LoggerPtr transcriptPtr = oap::getTranscript();
    std::string commentMsg("# Online help facilities are not yet implemented. Cannot look up ");
    if (func) {
        commentMsg += func;
    }
    else {
        commentMsg += "anything.";
    }

    LOG4CXX_INFO(transcriptPtr, commentMsg);
}

helpMimic.i
-----------
%module sample
 %{
#include <helpMimic.h>
 %}
class HelpMimic
{
public:
    HelpMimic() {};
    ~HelpMimic() {};

    char *__repr__();
    void operator()(const char *func=NULL);
};
Run Code Online (Sandbox Code Playgroud)

当我尝试在我的应用程序中使用此类时,我似乎无法获得我在帮助中看到的行为(下面的输出来自嵌入了Python的C++应用程序,其中每个输入行都通过其发送PyEval_String()):

 tam = sample.HelpMimic()
 tam   # echoes 'tam', nothing else
 print tam
 # _5010b70200000000_p_HelpMimic
 print repr(tam)
 # <Swig Object of type 'HelpMimic *' at 0x28230a0>
 print tam.__repr__()
 # Online help facilities are not yet implemented.
Run Code Online (Sandbox Code Playgroud)

最后一个打印显示该方法__repr__()存在,但我无法使用更简单的对象引用或使用它repr(tam).我也试图定义__str()__希望我误解哪些会被调用,但仍然没有运气.

我已尝试%extend在接口文件中使用该指令将一个__str__()或一个__repr__()定义插入到SWIG接口定义文件中,而不是直接在C++中定义它们,但无济于事.

我错过了什么?

dbn*_*dbn 3

正如 @flexo 在评论中建议的那样,如果您使用SWIG 代码生成器的-builtin标志repr(),则不会调用您的__repr__方法。相反,您需要定义一个适合 repr 槽的函数。

%feature("python:slot", "tp_repr", functype="reprfunc") HelpMimic::printRepr;
Run Code Online (Sandbox Code Playgroud)

根据 HelpMimic::printRepr 必须具有与预期签名匹配的签名(Python 文档中的 tp_repr) - 它必须返回字符串或 unicode 对象。另一个警告 - 你不能将相同的函数放入多个插槽中,所以不要尝试将其用于 tp_str!