Swig:如何将 C++ 字符串 const & 类型映射到 python 字符串?

Swig: How to typemap c++ string const & to python string?

我有一个带有这些原型的构造函数:

YCPTerm(const string& s);
YCPTerm(const string& s, const YCPList& l);
YCPTerm(bytecodeistream & str);

我正在使用 swig 生成 python 绑定。在 python 中,我尝试调用构造函数,并得到:

>>> import ycp
>>> ycp.YCPTerm("Empty")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ycp.py", line 575, in __init__
    this = _ycp.new_YCPTerm(*args)
NotImplementedError: Wrong number or type of arguments for overloaded function 'new_YCPTerm'.
  Possible C/C++ prototypes are:
    YCPTerm::YCPTerm(string const &)
    YCPTerm::YCPTerm(string const &,YCPList const &)
    YCPTerm::YCPTerm(bytecodeistream &)

我发现 this answer 这似乎是一个类似的问题,但类型映射类型检查对我不起作用。

这是我试过的:

%typemap(typecheck,precedence=141) const std::string& str {
   = Z_TYPE_PP($input) == IS_STRING;
}

我该如何解决这个问题?我需要输入输出类型映射来转换值吗?我已经 reading about typemap's here,但不确定如何对 const string& 进行类型映射。

我找到了answer here

将这些行添加到我的 .i 文件修复了错误:

%include std_string.i
%inline %{
using namespace std;
%}

虽然我不明白为什么。也许其他人可以回答。

std_string.i 库包含在 std::string 和 Python 字符串之间来回转换的 typedef。有关详细信息,请参阅 the documentation on the std::string library in SWIG