如何为 Python 2 中的字符串创建 SWIG return unicode 对象?

How can I make SWIG return unicode objects for strings in Python 2?

我有如下内容:

swigtest.cpp

#include <string>

class Foo {
public:
    std::string bar() {
        return "baz";
    }
};

inline Foo* new_foo() {
    return new Foo;
}

swigtest.i

%module swigtest
%{
#include "swigtest.hpp"
%}

%include <std_string.i>
%include "swigtest.hpp"

%newobject new_foo;

useswig.py

from swigtest import new_foo

foo = new_foo()
print(foo.bar())
print(type(foo.bar()))
$ swig -c++ -python -modern swigtest.i
$ g++ -fpic -shared -I/usr/include/python2.7 -DSWIG_PYTHON_2_UNICODE swigtest_wrap.cxx -lpython2.7 -o _swigtest.so
$ python2 useswig.py
baz
<type 'str'>

有什么办法让它输出

<type 'unicode'>

相反?我从 docs 了解到

When the SWIG_PYTHON_2_UNICODE macro is added to the generated code ... Unicode strings will be successfully accepted and converted from UTF-8, but note that they are returned as a normal Python 2 string

有没有办法实现这一点,可能以某种方式使用自定义类型映射?

自定义类型映射有效,但您需要更多来处理输入参数、输出参数等。

%module swigtest
%{
#include "swigtest.hpp"
%}

//%include <windows.i>  // Need for Windows DLLs to handle __declspec(dllexport)
//%include <std_string.i>
%typemap(out) std::string %{
    $result = PyUnicode_FromString(.c_str());
%}

%include "swigtest.hpp"

%newobject new_foo;

输出:

C:\test>py -2 useswig.py
baz
<type 'unicode'>